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

The expression ++[[]][+[]]+[+[]] might look confusing at first glance, but it involves a series of type coercions, array indexing, and unary operations in JavaScript that lead to the string "10".

Let's break down the expression step by step:

    [[]]: This is an array containing one element, which is an empty array.
    [+[]]: This is an array containing one element, which is the result of the unary + operator applied to 0, which is 0.

So far, we have:

lua

[[]]       => [ [] ]
[+[]]      => [ 0 ]

    ++[[]]: Here, ++ is the increment operator. It first converts the empty array [] to the number 0, increments it to 1, and then converts it back to an array [1].

lua

++[[]]     => [ 1 ]

    ++[[]][+[]]: This extracts the first element (which is 1) from the array [1] and increments it using the increment operator.

lua

++[[]][+[]] => 2

    Finally, ++[[]][+[]]+[+[]] concatenates the previous result (2) with the result of [+[]] (which is 0) using the + operator.

2 + 0       => 2

However, the result is treated as a number until explicitly converted to a string.

To convert the number 2 to a string, you can use the String() function or the .toString() method:

javascript

console.log(String(2));      // "2"
console.log((2).toString()); // "2"

So, in JavaScript, due to type coercion, when a number and a string are concatenated using the + operator, they are converted to strings and then concatenated. This leads to the final result "10".

javascript

console.log(2 + "0"); // "10"

Remember that while these kinds of examples are interesting to explore the nuances of JavaScript's type coercion, they can be confusing in practice. It's generally better to write clear and maintainable code for better readability and understanding.

Comments