Comparison operators are used in logical statements to determine equality or difference between variables or values.
JavaScript provides three different value-comparison operations:
This blog shows a brief concept explanation of == and ===
equality operators
Before learning about the equality operators, lets note what type conversion means to help us understand these operators
What is type conversion?
Type conversion (or typecasting) basically means transfer of data from one data type to another.
Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like JavaScript) automatically converts data types.
The source code can also explicitly require a conversion to take place, this is known as explicit conversion.
'==' operator:
Double equals('==') operator checks whether its two operands are equal and if they are of same data type, returning a Boolean result.
This operator tests for abstract equality(loose equality) i.e. it attempts to do the necessary type conversions before doing the equality comparison, it then returns true
if both the operands have same data type and returns false
if they have different data types.
'===' operator:
The triple equal(‘===’) will do the same comparison as double equals but without type conversion.
This operator tests for strict equality i.e it will not attempt do the type conversion hence it compares the variables as well the datatypes of these variables and returns true
only when both are equal.
Lets understand this with the help of an example:
if("3" == 3){
return true
}
else{
return false
}
// It will return true.
if("3" === 3){
return true
}
else{
return false
}
// It will return false.
In the above example, both the variables in if braces are equal i.e both are 3 but have different data types, one is string and the other one is number and since the "==" compares only variables, it returned true.
However, "===" returnes false since it compares variable as well as their data types.
Lets 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.
However, 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 "===" in Javascript.