I was preparing for an exam and found this (!+[]+[]+![]) expression and I'm wondering why it is equal to "truefalse" in javascript ?
I was preparing for an exam and found this (!+[]+[]+![]) expression and I'm wondering why it is equal to "truefalse" in javascript ?
The operators used here are:
!, negation, precedence 17+, unary +, precedence 17+, addition, precedence 14Spacing it out according to operator precedence:
(!+[] + [] + ![])
Evaluate the 3 expressions, then use addition on the three:
!+[]: unary + first coerces the empty array to a number. Arrays, when turned into primitives, have .join(',') called on them. Here, with no elements, the empty string is the result, and the empty string, when turned into a number, is 0, since it's falsey. Then ! inverts that and turns it into a boolean, making it true.
(true + [] + ![])
+ operates left-to-right. As said before, when the empty array is coerced to a primitive, it becomes the empty string. So true + [] results in true + '', resulting in the string 'true'.
('true' + ![])
Arrays are truthy. Invert the truthyness of that with !, and you get false:
('true' + false)
With +, when either side is not numeric, both sides get coerced to strings. The result is 'truefalse'.