Actually, for understand why you are getting that result, you have to think how the expression is evaluated (i.e, in what order?). If we observe your first expression:
const v = (! + [] + []);
we can see that there exists one logical operator (the logical NOT !
), one unary operator (+
) and one arithmetic operator, actually the addition +
. If we take into account the order of evaluation of that expression, we can write it like this:
const v = ( (!(+[])) + [] );
Now, the first expression evaluated here is +[]
, and from the documentation of the unary plus operator you get:
The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already...
Actually, the previous evaluation results in 0
(a coercion occurs in where the empty array is casted to number type) as you can check on next example:
So now, the expression is reduced to
const v = ( (!0) + [] );
Again, reading some documentation of this logical not operator you can found:
Returns false if its single operand can be converted to true; otherwise, returns true.
So, !0
is reduced to true
(another coercion occurs in where the number zero is casted to boolean type) as you can check on next example:
Now, we have next expression where the addition operator comes into play:
const v = ( true + [] );
The addition operator produces the sum of numeric operands or string concatenation.
In this case, the operator will do string concatenation since the operands aren't numbers. So, here is where a new coercion (basically a implicit cast of types) takes places again, because it need to convert both of the operand to strings:
true
is converted to string "true"
using the method toString()
of the Boolean type.
- and the empty array
[]
is converted to the empty string ""
using the available toString()
method of Array type.
And finally, our expression is reduce to:
const v = "true" + ""; // or simply "true".
const v = (! + [] + []);
console.log("value: " + v, "type: " + typeof(v));
The second expression should be easy to analyze for your own now, since it is a simplified version of the first one.