0

Is there a one-liner code where I can say the assigning of a variable is to a populated array from a choice of 2 array?

For example:

I'd like:

var myArray = ['a','b','c'];

The choice is between 2 arrays.

var a = [];
var b = ['a','b','c'];

So basically if var a is populated, I'd like myArray to = a. If var a is not populated but var b is populated, myArray = b; if var a and b are empty, then myArray = [];

I've tried the following to no avail:

var myArray = a || b || [];
asked Jan 15, 2015 at 23:43
1
  • A conditional operator? a.length > 0 ? a : b? Commented Jan 15, 2015 at 23:45

1 Answer 1

1
var myArray = (a.length) ? a : b;
answered Jan 15, 2015 at 23:45
Sign up to request clarification or add additional context in comments.

4 Comments

@JasonAller It would be a good homework for OP though. But no reason to check actually
no need. b acts as a failover to a and also as the empty double failover.
actually "it depends". Semantics of a || b || [] pseudo code and your statement are different
ahhh, i like the double failover..didnt think of just assigning regardless. Thanks

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.