Double Equals versus Triple Equals in JavaScript
Though they are both comparison equality operators in JavaScript, the triple equals, ===
, is what is called a strict equality operator, while the double equals, ==
, is a loose equality operator.
Strict equality
Strict equality compares both the value and type of the values on both sides of the ===
operator.
If the value is the same but the type is not, the equality check will evaluate to false. The values will be considered unequal if one of the values has a different type. With ===
, you are ensure that the values are strictly equal or identically equal because it never does type conversion.
4 === "4" // false
This expression will evaluate to false
. Though they appear to be of the same value, the left operand is of type number
while right operand is of type string
.
Loose equality
The double equals operator ==
performs type conversion on values if their types differ and then compares them for equality. If the types differ, either or both operands are first converted to a common type. The conversion rules are complex and depend on the types of the values compared.
4 == "4" // true
Why are these two deemed to be equal? This is because the ==
operator first converts the values before comparing them for equality.
4.toString() = "4" // first step: conversion
"4" == "4" // second step: comparison
Here is another example.
"0" == 0 // true because ToNumber("0") === 0
Using ==
can seem easier because type conversion is built-in, but be aware that it can give you unwanted results.
console.log(11 == "11"); // true
console.log(0 == false); // true
console.log(' \n\n' == 0); // true...really?
console.log(' ' == 0); // true...really?
Inequality
When writing a not-equals-to expression, the same rules above apply. However, instead of triple-equals (===
) versus double-equals (==
), it's a double-equals (!==
) versus a single equal (!=
).
Here are some examples with !=
.
console.log(11 != "11"); // false
console.log(0 != false); // false
console.log(' \n\n' != 0); // false (misleading)
console.log(' ' != 0); // false (misleading)
Here are some examples with !==
.
console.log(11 !== "11"); // true
console.log(0 !== false); // true
console.log(' \n\n' !== 0); // true
console.log(' ' !== 0); // true
Conclusion
The recommended approach is to stick to the Strict Equality operator ===
when possible. This will help maintain data type integrity throughout the project's codebase.
Keep in mind that these comparison operators are only for comparing primitive types. For comparing the deep equality of objects or arrays, a different approach will be needed.