In this specific example, there are three important points:
- What is the nature and behavior of the unary + operator
- What is the nature and behavior of the logical NOT operator.
- How the operators mentioned above interact with empty arrays
The unary + operator converts its operand (the value on the right) to a number. The logical operator NOT> either converts its operand to logical, or flips the value if the operand is already logical.
Both of these operators initially get the value of the operand before doing anything. Therefore, when the operand is an array, we need to understand what the value of the array is.
Let's try a few things first to learn how these operators behave with an array:
+[];
The + operator gets the value of its operand, and then converts it to a number. The operator ! gets the value of its operand, and then converts it to logical.
What if we have to use the operator twice ! and use the + operator for this resulting value?
!![];
Now we see the possibility of creating both the number 0 and the number 1. Given this strength, we can start to do some arithmetic (note that I use the grouping operator for readability:
(+!![]) + (+!![])
The result is 1 + 1 , equal to 2. Performing operations such as this is enough to achieve 36 will require quite a bit of confusion, but in the above example, the short-circuit add operator is used.
The addition operator performs string concatenation as well as numeric padding. Therefore, "foo"+"bar" returns "foobar". Similarly, numbers in string form will be combined, not added: "3"+"6" returns "36". The code in the question allows you to convert a number to a string by using the built-in array behavior:
["Hello"].toString();
With the addition operator, if either side of the operand is a string, the result will also be a string (see step 7 11.6.1 ). Since the .toString array method is called, the array creates an empty string. When this string is added to the type of number, a string of this number shows:
7 + "";
This can be used to combine rather than add two numbers. In the following example, I took our previous code, which led to 2 , and added a few more grouping operators for readability:
( ( +!![] ) + [] ) + ( ( +!![] ) + [] )
On the left side of the middle + operator, we generate number one and add it to the line created by the empty array. Then we do the same with the value on the right side of the middle + operator. Result: two lines with a value of "1" . The middle statement then concatenates the two lines, giving "11" .
Given this knowledge, you can review the code in your question and quickly figure out the individual parts.