5

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.
1
  • why you don't want to add if condition? Commented Jul 14, 2017 at 14:50

2 Answers 2

8

Do this:

[item1, item2, item3, item4, item5] = exampleResult || [];
Sign up to request clarification or add additional context in comments.

4 Comments

Not very elegant in the sense that it produces undefined, undefined, undefined, undefined, undefined
I know, indeed. But perhaps this exactly what he wants.
True, OP asks "Is there a way to solve it?" and this solves it :)
@HenriqueOeckslerBertoldi thanks this is what I need. It works!
3

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.