I want to loop over an array called children
which may or may not be defined.
Currently I'm doing this:
var i;
var foo = {/*"children": ["1","2","3","4"]*/};
for (i = 0; i < [foo.children || []][0]. length; i += 1) {
console.log("hello")
}
This works correctly, because in case children
is undefined, [foo.children || []][0]
ends up being [[]]
whose first element is an empty array []
.
Question:
Is there any way to leave away the outer array?
I don't want to use an if-clause testing for children, just modify the array.
One way would be:
for (i = 0; i < foo.children.length || [].length; i += 1) {
console.log("hello")
}
but I'm looking for other alternatives if exist.
Thanks
EDIT: Here is a jsperf on all variants. Interesting...
if
clause? That would be the normal way, unless you're trying to write deliberately obfuscated code. – Alnitak Feb 11 at 9:34children
to default to an empty array instead of not existing at all. – Alnitak Feb 11 at 9:36length
expression out of thefor
loop, into its own variable. This avoids re-evaluating that expression for each iteration. – Alnitak Feb 11 at 10:00