Equality Operator : == VS === in JavaScript

Equality Operator : == VS === in JavaScript

In this post, we'll learn about the difference between the == and === operators in JavaScript, and when to use each one.

By now, you are already aware that there are two types of equality operators in JavaScript, but you've probably wondered why that is, and when to know which one to use.

The == Operator

The double equal == operator, or abstract comparison operator, is used to check if the two values are equal, regardless of their type. If they are equal, it will return true, otherwise, it will return false.

This means that when you use the == operator, it will return true when comparing 18 and "18", because they are of the same value.

const age = "19"
    if(age == 19){
    console.log("loose equality operator");
}

This doesn't happen only with numbers, but anything that can be converted, such as strings, booleans, and nulls. Because of this, things will be equal using the == operator, but not using the === operator.

When this conversion of type happens, it is called type coercion.

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).

let x = 10 + '20'; //The Number 10 is converted tostring '10' and then '+' concatenates both strings 
let y = 10 - '5'; //The string '5' is converted to number 5 implicitly
console.log(x);
console.log(y);

The === Operator

The triple equal === operator, or strict comparison operator, is used to check if the two values are of the same type and have the same value. If this is the case, it will return true, otherwise it will return false.

We say "type", we mean whether or not the value is a number, string, boolean, or null.

This means that when using ===, it will return false when comparing 18 and "18", because they are not of the same type.

const age = 19
    if(age === 19){
    console.log("strict equality operator");
}

It does not perform type coercion.

So, each operator has its own advantages and disadvantages, the === operator is the recommended operator to use when comparing values. Because it is more strict than the == operator.

This isn't to say to never use ==, just to be careful and truly understand what is going on under the hood before using it.

Hopefully, you've found this post helpful and have learned something new!