==
is the abstract equality comparison operator and ===
is the strict equality comparison operator. They both are ways to check for equality. They check if something on the left is equal to something on the right.
The difference between these two is that the abstract equality operator doesn’t care about the data types, whereas the strict equality operator does.
x == y //abstract equality comparison operator
x === y //strict equality comparison operator
// Double Equalsconsole.log(2 == "2"); // trueconsole.log(0 == ""); // trueconsole.log('4' == 7) // falseconsole.log(null == undefined); // trueconsole.log([] == ""); // true// Triple Equalsconsole.log(2 === "2"); // falseconsole.log(0 === ""); // falseconsole.log('A' === 'A') // trueconsole.log(null === undefined); // falseconsole.log([] === ""); // false
Lines 2 to 6 show four different examples of the double-equal operator using javascript.
2 == "2"
, the abstract equality operator returns true
because the "2"
is converted to the number 2 before the comparison is made.0
and an empty string ""
. The empty string is coerced into a number (0), and since both sides are equal numbers, the comparison evaluates to true.'4'
is compared to the number 7
. The string is coerced into a number, but the resulting values are not equal, so the comparison evaluates to false.null
and undefined
. In JavaScript, null and undefined are loosely equal to each other, so the comparison evaluates to true.[]
to an empty string ""
. Due to some peculiarities of JavaScript’s type coercion, the comparison evaluates to true. However, it’s generally recommended to avoid using loose equality with arrays and strings in this manner because it can lead to unexpected behavior.Same as above, lines 8 to 12 show five different examples of the triple-equal operator using javascript.
2 === "2"
, the strict equality operator returns false
because it sees that the data types are different.null
and undefined
to be equal, so the comparison evaluates to false.The abstract equality operator coerces data types and leads to interesting results.
The strict equality operator does not do type conversions and leads to more predictable results. It is always better to use the strict equality comparison ===
operator.
In conclusion, general difference between these two comparison operators is discussed in the below table.
Double-equals | Triple-equals |
---|---|
Comparision of variables and values with no data-type restriction. |
Comparision of variables and values with data-type restriction. |
Variables and values may not be of the same type for a TRUE comparison. |
Variables and values should be of the same type for a TRUE comparison. |
Examples: ‘2’ == 2 corresponds to TRUE result. |
Examples: ‘2’ === 2 corresponds to FALSE result. |
‘A’ == ‘A’ -> True |
‘A’ === ‘A’ -> True |
5 == ‘5’ -> TRUE |
5 === ‘5’ -> FALSE |
4 == 7 -> FALSE |
4 === 7 -> FALSE |