JavaScript Array destructuring assignment and null value

Viewed 3739

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 assignment to set the value of those items which is working fine like this (just an example):

var item1, item2, item3, item4, item5;
//var result = getListOfItemsFromServiceA(1622);
var exampleResult = ['item1', 'item2', 'item3', 'item4', 'item5'];
[item1, item2, item3, item4, item5] = exampleResult;
console.log(item1, item2, item3, item4, item5);

The problem I have is that in some cases getListOfItemsFromServiceA(id) returns null for example when the id is not found in the database. So my code is not working:

var item1, item2, item3, item4, item5;
//var result = getListOfItemsFromServiceA(1622);
var exampleResult = null;
[item1, item2, item3, item4, item5] = exampleResult;
console.log(item1, item2, item3, item4, item5);

Is there a way to solve this using Array destructing syntax instead of adding an if condition like if(getListOfItemsFromServiceA(1622) !== null)?

Note

  • I can't change the code of getListOfItemsFromServiceA.
2 Answers
Related