MyBlogs

Getting started | Learn "==" and "===" operators

10 December, 2020

In one word, main difference between "==" and "===" operator is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn't allow that, because it not only checks the value but also type of two variable, if two variables are not of the same type "===" return false, while "==" return true.

Difference between "==" and "===" Equal Operator

Since JavaScript support both strict equality and type-converting equality, it's important to know which operator is used for which operation. As I said that, "===" takes type of variable in consideration, while "==" make type correction based upon values of variables.

When we compare two variables of different types eg. a boolean with the string or a number with the string using "==" operator,it automatically converts one type into another and return value based upon content equality, while "===" is strict equality operator in JavaScript , it also checks the type of variables hence return false and returns true only if both the variables are of same type and contains same value.

This will be much clear with following examples of "==" and "===" operator in JavaScript :

Example-1:

var a = "123";
var b = 123;
if( a == b )
{
console.log("true")
}
else{
console.log("false")
}

// true, because auto type convertion, number converted into string

Example-2:

var a = "123";
var b = 123;
if( a === b )
{
console.log("true")
}
else{
console.log("false")
}
// false, because type of both the operands are different

Example-3:

var a = false;
var b = 0;
if( a == b )
{
console.log("true")
}
else{
console.log("false")
}
// true, because false is equivalent of 0

Example-4:

var a = true;
var b = 1;
if( a == b )
{
console.log("true")
}
else{
console.log("false")
}
// true, because true is equivalent of 1

Example-5:

var a = false;
var b = 0;
if( a === b )
{
console.log("true")
}
else{
console.log("false")
}
// false, because variable 'a' is a boolean type and variable 'b' is number

That's all about difference between "==" and "===" JavaScript operator , you should always use strict equality operator i.e. === and avoid using == operator even if you need type convertion, instead convert the type by yourself to make it more readable. By the way, it's one of the interesting JavaScript interview Question, and you can expect in beginner level JavaScript interviews.

I hope you like this blog and all your doubts and confusions between "==" and "===" Operator are cleared .

Thanks for reading!!