I have recently seen an expression from a source, which looks something like below -
++[[]][+[]]+[+[]]
Entering this into the Chrome (Windows 7, Version 27.0.1453.94 m) console shows a result of "10"
.
Can someone explain what's happening here?
JSFiddle.
JavaScript is fairly flexible about converting between data types. The first thing to notice is that +[]
evaluates to 0.* That lets us rewrite the expression as:
++[[]][0] + [0]
The next thing to notice is that ++[[]][0]
is the preincrement operator applied to the first element of [[]]
. Normally you can't apply ++
to an array, but JavaScript kindly converts the first element to 0
, so the result is that ++[[]][0]
evaluates to 1
(the first element of [[]]
having now been incremented). It is kind of like this:
var a = [[]];
var b = ++a[0];
// now a will be [1] and b will be 1
That leaves us with:
1 + [0]
JavaScript now converts the int and the array to strings (since [0]
is not a numeric value) and concatenates them together. Done!
* My understanding of how +[]
becomes 0
is that it is a two-step process: first, []
is converted to a string primitive, which is the empty string. The empty string then converts to a number, which is zero. Via the same route, [1]
evaluates to '1'
and then to 1
, [2]
evaluates to 2
, etc. However, [1, 2]
evaluates to '1,2'
which evaluates to NaN
. (The last because the decimal point separator is .
, not ,
. I don't know what would happen if my locale were different.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With