"==" VS "===" in JavaScript

ยท

2 min read

So, let's get started:

"==" operator compares variables but not their datatypes.

However "===" operator compares the variables as well the datatypes of these variables and returns "true" only when both are equal.

Let's understand it with an example:

if("5" == 5){
      return true
}
else{
      return false
}
// It will return true.



if("5" === 5){
     return true
}
else{
     return false
}
// It will return false.

In the above example, both left hand side and right hand side variable is equal but have different data types that is, one is string and the other one is number and since the "==" compares only variables, it returned true. However, "===" returned false since it compares variable as well as their data types.

Let's see another example:

console.log(null == undefined ? true : false)                 //true

console.log(null === undefined ? true : false)              //false

In the above example, "null" has object data type and "undefined" has undefined data type. Since the structure of both the "null" and "undefined" is same, "==" returned true but as we can see both "null" and "undefined" belong to different data types, "===" returned false.

Although it varies from case to case, it is generally safe to use "===".

I write articles related to web development. Follow me here if you are learning the same.

If you love the article follow me on Twitter: @therajatg

If you are the Linkedin type, let's connect: linkedin.com/in/therajatg

Have an awesome day ahead ๐Ÿ˜€!

ย