This is valid and returns the string "10"
in JavaScript (more examples here):
console.log(++[[]][+[]]+[+[]])
Why? What is happening here?
This is valid and returns the string "10"
in JavaScript (more examples here):
console.log(++[[]][+[]]+[+[]])
Why? What is happening here?
+'' or +[] evaluates 0.
If we split it up, the mess is equal to:
In JavaScript, it is true that
+[] === 0
.+
converts something into a number, and in this case it will come down to+""
or0
(see specification details below).Therefore, we can simplify it (
++
has precendence over+
):Because
[[]][0]
means: get the first element from[[]]
, it is true that:[[]][0]
returns the inner array ([]
). Due to references it's wrong to say[[]][0] === []
, but let's call the inner arrayA
to avoid the wrong notation.++[[]][0] == A + 1
, since++
means 'increment by one'.++[[]][0] === +(A + 1)
; in other words, it will always be a number (+1
does not necessarily return a number, whereas++
always does - thanks to Tim Down for pointing this out).Again, we can simplify the mess into something more legible. Let's substitute
[]
back forA
:In JavaScript, this is true as well:
[] + 1 === "1"
, because[] == ""
(joining an empty array), so:+([] + 1) === +("" + 1)
, and+("" + 1) === +("1")
, and+("1") === 1
Let's simplify it even more:
Also, this is true in JavaScript:
[0] == "0"
, because it's joining an array with one element. Joining will concatenate the elements separated by,
. With one element, you can deduce that this logic will result in the first element itself.So, in the end we obtain (number + string = string):
Specification details for
+[]
:This is quite a maze, but to do
+[]
, first it is being converted to a string because that's what+
says:ToNumber()
says:ToPrimitive()
says:[[DefaultValue]]
says:The
.toString
of an array says:So
+[]
comes down to+""
, because[].join() === ""
.Again, the
+
is defined as:ToNumber
is defined for""
as:So
+"" === 0
, and thus+[] === 0
.