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?
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?
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.)
This expression stringifies valid Javascript constructs that yelds NaN
, numbers, boolean undefined
etc.
e.g.
+[] -> 0 //The unary plus operator is applied to the result of toString applied to an empty array (which is an empty string)
!+[] -> true
You can have a look also at this question, and at the no alnum cheat sheets.
+[]
is a number conversion from array to number which is 0.
and +[0]
is also 0.
So the final result can be deduced to (++0) + [0]
which is 1+[0]
.
And for a number adding an array. They are converted to string so the result is actually '10'.
You can log typeof(++[[]][+[]]+[+[]])
to verify.