〰️ Why does ‘’ == 0 returns true in JavaScript?

Understanding the loose equality operator

The loose equality operator (==) checks for the equality of two values and the result, as opposed to the strict equality (===), depends on the type of these values. So even if two things look very different, this operator can say they are the same. For example:

'' == 0; // true
'' == []; // true
undefined == null; // true

Comparing Strings against Numbers

The ECMAScript documentation states that if a String value is compared against a Number value then the String one needs to be converted to Number first.

Let's apply this to our example: '' == 0

First, the '' is converted to a number, since its an empty string it will result in a 0.

Now the expression would become 0 == 0, which logically returns true.

A word of caution 🚨

Due to its nature, the loose equality can return unexpected results, so you should be very careful when using it. Here are some examples of why:

true == 0; // false but
true == 1; // true but
true == 2; // false again 🤷‍♂️

undefined == null; // true

new Boolean(false) == false; // false