Determining if an array is empty
The empty array is truthy in JavaScript, i.e. []?b:c
returns b
. This leaves us to find our own ways to determine if an array is empty. The most obvious way is .length
:
a.length?b:c
However, this can be shortened by 2 bytes with the in
operator:
0 in a?b:c
Note: unlike in Python, x in y
checks whether y
has a key x
; it's a shorthand for y.hasOwnProperty(x)
.
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:
a[0]?b:c
This works iff the first item in a
is guaranteed to be truthy. For example, a=[1];a[0]
returns 1
, which is truthy; a=[];a[0]
returns undefined
, which is falsy; but a=[0];a[0]
returns 0, which is also falsy. But in general, this trick works on arrays of chars or positive numbers.
a+""?b:c
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.
Caveat: If 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.
a+a?b:c
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.
var
)? And should JavaScript golf code be a function or output something directly? I honestly think this can make much difference. \$\endgroup\$(class{static #x = 1;get #y(){};set #y(z){}})
can be rewritten as(class{static#x = 1;get#y(){};set#y(z){}})
. This makes for some nice obfuscation, too, but I can’t think of a practical example in code golf. \$\endgroup\$