JavaScript Quirk - Increment on array -
why is
++[[]][0] == 1 but does
++[] throw error
aren't same? believe first example executes index-read on array array in array. , increment executed. if why can't second example?
++ assignment operator. requires valid left-hand-side operand (even though can on right of ++).
[] value, not can assign to.
[[]][0] evaluates [] valid left-hand-side, because points element in existing array. works.
to give less confusing example:
var = 1 1++ // throws error a++ // works fine it doesn't matter value in a. worst case, ++ return nan, never error, long can assign result.
the javascript quirkiness in example +[] + 1 evaluates 1 because empty array coerced empty string, explicitly 0 (+"" 0), added 1.
the ++ operator coerces number, unlike + satisfied "" (so [] + 1 turns "" + "1"). thus, when decomposing ++, don't forget force operands number (not matters in example).
Comments
Post a Comment