Why 0 == [], but 0 == false and! [] == false?

At least in JavaScript, the following is true:

0 == [] // true 0 == false // true ![] == false // true 

Why? I know that == means equals, but not equal to type, but how false == true , so to speak, in this case?

+5
source share
2 answers

JavaScript coordinates objects with Boolean values ​​using the lax equality operator.

 0 == [] 

because JavaScript supports both values ​​(both of them are not the same type) for boolean values ​​to compare them. In other words, false == false .

If you use === , on the other hand, you check the equality of the object.

An interesting use case would be the following:

 [] === []; // => false 

This is because === checks the memory location of objects. Two arrays do not have the same memory location. But:

 var arr = []; arr === arr; // ==> true 

But here is another interesting twist:

 1 === 1; // ==> true 

In the case of arrays and simple objects, JavaScript refers to a memory location. But with values ​​such as strings and numbers, JavaScript checks to see if these values ​​are absolutely equal with the === operator.

So the big difference comes down to the differences in == and === , as well as how JavaScript uses types.

Tip . That's why it is usually recommended to use the strict operator === if you need to prevent coercion (however, sometimes coercion can work in your favor, for example, when working with the -browser cross, where the value can be undefined in one browser but null in another browser. Then you can say something like !!thatStrangeValue , and both undefined and null will be forced to the same thing).

Edit

OP raised a good point:

 [] == false; ![] == false; 

The above statements are correct, which is strange. I would say that the first statement checks the void, and the second checks the existence. Does anyone know the answer to this last question?

+3
source

There are two types of equality in JavaScript. There is equality of value, which is represented by == and equality of value and type, which is represented by === . The latter is a strict equality operator.

In your case, we check equality only by value, and not by type.

[] represents an empty object, that is, [] and 0 have the same value.

In JavaScript, the value of any number greater than or equal to 1 is true , and the value 0 is false

Hope this helps

+1
source

All Articles