Determining if an array is empty
b. This leaves us to find our own ways to determine if an array is empty. The most obvious way is
However, this can be shortened by 2 bytes with the
0 in a?b:c
Note: unlike in Python,
x in y checks whether
y has a key
x; it's a shorthand for
This is, I believe, the shortest code that unconditionally detects whether
a is empty. However, there are a few alternatives that work in various scenarios:
This works iff the first item in
a is guaranteed to be truthy. For example,
1, which is truthy;
undefined, which is falsy; but
a=;a returns 0, which is also falsy. But in general, this trick works on arrays of chars or positive numbers.
When arrays are casted to strings, the brackets are left out.
[1,2,3]+"" returns the string
"1,2,3". So casting
a to a string will return the empty string (falsy) for the empty array, and a truthy string otherwise.
a contains a single array which contains either nothing or a single array containing... etc., e.g.
[[[[[]]]]], it will still be casted to the empty string.
This is practically exactly the same as the above example, but a byte shorter. When
+ is called on two arrays, JS stupidly converts them both to strings and concatenates those. So
a+a returns exactly the same thing as
a+"", but doubled.