I was preparing for an exam and found this (!+[]+[]+![]) expression and I'm wondering why it is equal to "truefalse" in javascript ?
-
it's due to type coercion, unary +, and boolean operations – Bravo Dec 07 '20 at 00:52
-
1Empty array toString gives `""`, `+""` gives `0`, `!0` gives `true` etc... – Roko C. Buljan Dec 07 '20 at 00:58
-
1Related: [Why does ++\[\[\]\]\[+\[\]\]+\[+\[\]\] return the string "10"?](https://stackoverflow.com/q/7202157/4642212). When trying to figure this out yourself, where exactly was the difficulty? – Sebastian Simon Dec 07 '20 at 07:23
1 Answers
The operators used here are:
!, negation, precedence 17+, unary +, precedence 17+, addition, precedence 14
Spacing 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'.
- 356,069
- 52
- 309
- 320
-
great answer, there's a lot of important basics here. i didn't even know you could concat a boolean to get the string "true". – But those new buttons though.. Dec 07 '20 at 01:08