Why (!+[]+[]) is 'true' and (false + []) is 'false' in Javascript,?

  • A+
Category:Languages

I'm looking at ECMA-262 grammar for a definition of the next code bellow:

const v = (! + [] + []); const c = (false + []);  console.log(v); console.log(c);

What is BEHIND it?

Until now I did not find anything helpful, does anyone know why it gives those results or have references about it?

 


This is because when you try to apply an operator to different data structure JavaScript engine applies coercion.

In the first case what it does is :

  1. Convert first [] to primitive, which is performed by invoking toString() method of array. The toString method joins all the array values to a string. If you wold have something like (false + [1,2,3]) you would get : false1,2,3

  2. The second step is to bring the boolean in the String context

  3. Now that we have all the values in the same datastructure, it will simply concatenate all of them

In your case (! + [] + []) is evaluated to 'true' which has the length of 4.

The book You Don't Know JS: Types & Grammar is a gem for understanding all these kind of weird operations JavaScript engine does.

EDIT: As Felix Kling was suggesting ! operator has a different role in the evaluation of (! + [] + []).

In this case what happens is that :

  • ! + [] is evaluated to true. This is because ! + [] puts them in a Boolean context where [toNumber] operation is applied on [] which is 0 and !0 is true

  • true + [] is evaluated to 'true'. This is because when you try to add a boolean with an object (array is derived from object) [toString] operation is applied to both items.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: