This is valid and returns the string "10" in JavaScript (more examples here):
console.log(++[[]][+[]]+[+[]])
Why? What is happening here?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 arrayAto avoid the wrong notation.++before its operand means “increment by one and return the incremented result”. So++[[]][0]is equivalent toNumber(A) + 1(or+A + 1).Again, we can simplify the mess into something more legible. Let’s substitute
[]back forA:Before
+[]can coerce the array into the number0, it needs to be coerced into a string first, which is"", again. Finally,1is added, which results in1.(+[] + 1) === (+"" + 1)(+"" + 1) === (0 + 1)(0 + 1) === 1Let’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.In this case,
+sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string"0", next, the number is coerced into a string ("1"). 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
.toStringof an array says:So
+[]comes down to+"", because[].join() === "".Again, the
+is defined as:ToNumberis defined for""as:So
+"" === 0, and thus+[] === 0.