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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -