In JavaScript for checking equality or comparison we have two operators.
- == Double equals operator known as loose equality or abstract comparison
- === Triple equals operator known as strict equality or strict comparison
Now the main difference between two operators is that == does type coercion before comparison but ==== does not convert and compares as it is.
Type coercion:
Type coercion is automatic or implicit conversion of one data type to another. It is similar to type conversion and the only difference is type conversion can be implicit or explicit. But type coercion can only be implicit.
Both comparison operators return Boolean value TRUE or FALSE
== or === Operator
If both are number data type it returns TRUE only when both value matches otherwise FALSE
var a = 10;
var b = '10';
console.log(a == b);
console.log(a === b);
Output:
True
False
If a string is compared to number, number gets converted to string and then compared
Which comparison operator should I use?
Always use strict comparison operator (===) as it will compare both the operand and data type. Using loose comparison operator (==) will lead to strange results in programming.
For example,
Using == operator
false == 0 // true
false == "" // true
0 == "" // true
undefined == null // true
[] == false // true
[] == 0 // true
It performs type coercion and returns the result. But originally each one is of different data type 0 is number, false is Boolean type.
false === 0 // false
false === "" // false
0 === "" // false
undefined === null // false
[] === false // false
[] === 0 // false
Points to note:
- === does not coercs and just compares the operands as it is and returns the results. So it is always best to use === operator
- == does implicit coercion and convert from one type to another implicitly leading to strange results.