Communities for your favorite technologies.  Explore all Collectives

Why does ++[[]][+[]]+[+[]] return the string "10"?

submited by
Style Pass
2024-10-07 06:30:04

Communities for your favorite technologies. Explore all Collectives

Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

In JavaScript, it is true that +[] === 0. + converts something into a number, and in this case it will come down to +"" or 0 (see specification details below).

[[]][0] returns the inner array ([]). Due to references it's wrong to say [[]][0] === [], but let's call the inner array A to avoid the wrong notation.

++ before its operand means “increment by one and return the incremented result”. So ++[[]][0] is equivalent to Number(A) + 1 (or +A + 1).

Before +[] can coerce the array into the number 0, it needs to be coerced into a string first, which is "", again. Finally, 1 is added, which results in 1.

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.

Leave a Comment
Related Posts