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
KingKongFrog
14.5k22 gold badges78 silver badges135 bronze badges
1 Answer 1
var myArray = (a.length) ? a : b;
answered Jan 15, 2015 at 23:45
SeanCannon
78.1k17 gold badges126 silver badges145 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
zerkms
@JasonAller It would be a good homework for OP though. But no reason to check actually
SeanCannon
no need. b acts as a failover to a and also as the empty double failover.
zerkms
actually "it depends". Semantics of
a || b || [] pseudo code and your statement are differentKingKongFrog
ahhh, i like the double failover..didnt think of just assigning regardless. Thanks
lang-js
a.length > 0 ? a : b?