'==' vs '===' in Javascript

'==' vs '===' in Javascript

What is the difference between the ‘double equals’ and the ‘triple equals’ operators?

The most straightforward answer would be: “The triple equals operator (‘===’) compares both type and value, while the double equals (‘==’) only compares value.”

This begs a practical example:

console.log(1 == 1);
//true

console.log(1 =='1');
//true

In the first example, we log to the console a comparison using '=='. "Is 1 equal to 1"? Yes. In the second example, we make another loose comparison using '==', but this time we are comparing the number 0 to the string '0'. While they look similar to the eye we know that a string and a number look very different in computer memory. So how does it happen that these two operands are the same?

The answer to this is '==' operator implicit coercion, which means it converts variable values to the same type before comparison. Double equals are officially known as the abstract equality comparison operator or loose equality, it will compare two elements irrespective of their datatype.

How to tackle this situation?

Triple Equals(===):

Triple equals are termed the strict equality comparison operator or identity operator, but it will compare two elements by value and datatype. Strict operators do not convert the variable values to the same type before performing a comparison but instead, it returns true only if both values and types are identical for the two-variable in comparison.

console.log(1 === 1);
//true

console.log(1 === '1');
//false

In the second example, there is no type conversion before checking. so the output is false.

When to Use == vs ===?

As a general rule, you should always use the '\===' operator, if you do not want to utilize type coercion. The '\==' operator can cause problems because of type coercion and may lead to bugs in your code.

If you need to compare two values that could be different types, then you can use the '\==' operator. Just be aware that this operator may cause unexpected results.

I hope this clears up any confusion you had about the difference between the loose equality operator and the strict equality operator.

Thank you for reading. Happy coding!