Equality Operator (==)
The Equality operator is a logical operator in JavaScript which compares two Values and gives the Output as True if they are Equal and False if they are not equal in nature.
This is important as it Equality Operator does not compare the Type of values we are comparing but instead, only compares their values.
The following code snippet will explain the Equality Operator with an example:
let a = '5' ; // Integer Variable
let b = 5; // String Variable
if(a==b){
print("True")
}else{
print("False")
} //This Statement Prints True even though one of the Value is String and another value is an Integer
//Comparing Null and Undefined
null == undefined //True
If you run the above code, you will get "True" as an output even though the datatype of the variables a and b are different.
This can create ambiguity in Code. To circumvent this issue, A Strict Equality Operator should be used.
Strict Equality Operator (===)
The strict equality Operator also compares the values but it also checks the 'Type' of the variable we are comparing which solves the issue with \== operator.
Comparing Type of variables solves the ambiguity in code and also makes the code robust
Let's compare the previous examples with (\===) operator:
let a = '5' ; // Integer Variable
let b = 5; // String Variable
if(a===b){
print("True")
}else{
print("False")
} //This Statement Prints False as both the Types are different.
//Comparing Null and Undefined
null === undefined //False
Why Does == returns true for different datatype but the same values?
When both operands are of different datatypes, \== performs a type conversion of one operand to make datatypes of both operands safe thus comparing just the value whereas \=== operator doesn't perform any datatype conversion.