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!!!.