Destructuring with default values in JavaScript
Destructuring is a useful JavaScript ES6 feature. I am pretty sure a lot of JavaScript developers utilize this feature to extract properties from objects or arrays.
const templateData = {exportData: [], downloadData: []};
const {exportData, downloadData} = templateData || {};
/* we can then loop through the `exportData` array
* using .map() or any of the es6 functions to iterate over an array.
*/
Looks neat and simple, right?
What if exportData is an API response data that returns an undefined or null instead of an []?
With this, looping through the exportData will crash the app.
// We get an error like
TypeError: Cannot read properties of undefined (reading 'map').
To avoid this scenario, destructuring allows us to provide a default value.
const {exportData = [], downloadData = []} = templateData || {};
/* we can then loop through the `exportData` array
* using .map() or any of the es6 functions to iterate over an array.
* without crashing the app
*/
Now, to the main part.
Providing default values in destructuring assignment works only if there is no variable or its value is set to undefined. Any other value, including null, false and 0, are still values.
To resolve this, we do…
const downloadData = templateData?.downloadData || [];
const exportData = templateData?.exportData || [];
Thanks for reading!!!.
Hello Ayo. Nice content.
I used to set default values before, but now I’d rather verify the integrity of
templateData
before attempting to destructure it.Yeah sounds like a good approach. Just a question though: how do you verify the integrity of
templateData
if it is a big object?For example, if templateData is generated by a function/method call, you can return an object with
templateData
as thedata
property, and also return anerror
property. In your code, you would handle the error first. If there’s no error, then you can proceed to the happy path & destructure in peace