Javascript Array Destructuring Assignment And Null Value
I'm using an external service getListOfItemsFromServiceA which accepts an id (of user) and returns a list of 5 items (exactly 5) associated to this user. I used Array destructuring
Solution 1:
Do this:
[item1, item2, item3, item4, item5] = exampleResult || [];
Solution 2:
You can add a fallback if exampleResult is null :
var item1, item2, item3, item4, item5;
var exampleResult = null;
[item1, item2, item3, item4, item5] = exampleResult || [];
console.log(item1, item2, item3, item4, item5);
This produces undefined, undefined, undefined, undefined, undefined
.
You can also set default values to the destructured variables :
var item1, item2, item3, item4, item5;
var exampleResult = null;
[item1="", item2="", item3="", item4="", item5=""] = exampleResult || [];
console.log(item1, item2, item3, item4, item5);
Post a Comment for "Javascript Array Destructuring Assignment And Null Value"