YentheO
YentheO

Reputation: 317

JavaScript Quirk - Increment on array

Why is

++[[]][0] == 1

But does

++[]

throw an error

Aren't they the same? I would believe the first example executes an index-read on the array so you get the array in the array. And then the increment is executed. If so than why can't I do the second example?

Upvotes: 0

Views: 142

Answers (1)

Touffy
Touffy

Reputation: 6561

++ is an assignment operator. It requires a valid left-hand-side operand (even though it can be on the right of ++).

[] is only a value, not something you can assign to.

[[]][0] evaluates to [] but it is a valid left-hand-side, because it points to an element in an existing array. So that works.

To give a hopefully less confusing example:

var a = 1
1++ // throws an error
a++ // works fine

It doesn't matter what value is in a. Worst case, ++ will return NaN, never an error, as long as it can assign the result.

The only JavaScript quirkiness in your example is that +[] + 1 evaluates to 1 because the empty array is coerced to an empty String, then explicitly to zero (+"" is 0), which is then added to 1.

The ++ operator always coerces to number, unlike + which would be satisfied with "" (so [] + 1 turns into "" + "1"). Thus, when decomposing a ++, don't forget to force the operands to number (not that it ultimately matters in your example).

Upvotes: 5

Related Questions