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?
-
BTW this isn't a JavaScript-specific "quirk". Any language that has assignment operators will behave similarly, although some might statically prevent you from writing useless statements like the first one and some might refuse to take an array as an operand to addition.Touffy– Touffy2015年09月30日 08:48:04 +00:00Commented Sep 30, 2015 at 8:48
1 Answer 1
++ 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).
5 Comments
++[[]][+[]] [[]][+[]] = [[]][+[]] + 1; [[]][0] = [[]][0] + 1; [[]][0] = [] + 1; [[]][0] = "" + "1"; // +-operator prefers string concatination, empty array = "" ["1"] // the first value of the array is replaced by "" + "1"+[]) :p You got the evaluation order mostly right, except that the top priority is actually +[] which evals to zero before anything else.++ coerces to number (unlike += 1 which is truly equivalent to = X + 1) so it doesn't happen exactly the same as in my post. In your "puzzle" here, the first part evals to the number 1 (by coercing the empty array to "" and then to 0, and adding 1) rather than the string "1". It is then coerced to a string because the second part ([0]) is coerced to "0".++.