3

I was preparing for an exam and found this (!+[]+[]+![]) expression and I'm wondering why it is equal to "truefalse" in javascript ?

Zouhair Dre
  • 558
  • 4
  • 14

1 Answers1

5

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'.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320