DEV Community

Rajat Gupta
Rajat Gupta

Posted on

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

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.

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 "===".

Hope, you liked the article.
If it added any value, consider giving a ❤️.

Top comments (0)