Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

At least in JavaScript the following are true:

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

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

like image 922
Frederik Witte Avatar asked Sep 28 '22 21:09

Frederik Witte


1 Answers

JavaScript coerces objects to boolean values when using the non-strict equality operator.

0 == []

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

If you use ===, on the other hand, you're checking object equality.

An interesting use case would be this:

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

This is because === is checking the memory location of the objects. Two arrays don't share the same memory location. However:

var arr = [];

arr === arr; // ==> true

But, here's another interesting twist:

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

In the case of arrays and plain objects, JavaScript references the memory location. But with values like strings and numbers, JavaScript checks whether the values are absolutely equal with the === operator.

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

Hint: This is why it's usually recommended that you use the strict === operator if you need to prevent coercion (however, sometimes coercion can work to your benefit, for example when working with cross-browser issues where a value might be undefined in one browser but null in the other browser. Then you can say something like !!thatStrangeValue, and both undefined and null will be coerced to the same thing).

Edit

OP brought up a good point:

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

The above statements are both correct, which is strange. I would say the first statement is checking for emptiness, while the second one is checking for existence. Anyone know the answer to this last point?

like image 180
Josh Beam Avatar answered Oct 03 '22 01:10

Josh Beam