Table of contents
JavaScript has two types of operators for comparing the operands. One is the equality operator (==
) and the other one is the strict equality operator(===
). Let us see how these operators differ from one another and how and where we might apply them.
==
operator
In JavaScript, the loose equality operator is denoted by the symbol ==
. Its task is to determine whether or not the operands on either side of this operator are equal. It consistently yields a Boolean outcome.
When both operands are equal, the function returns true
; when they are not, it returns false
.
The equality operator does the implicit type coercion of the operands passed around it. Type coercion refers to the process of converting the data types of the operands on both sides of the operator.
If one operand is a number and the other one is a number within quotes, which becomes a string, then the equality operator will convert the number to a string or it will convert the string into a number.
console.log(1 == '1') // true
console.log(true == 1) // true
console.log("Hello" == "Hello") // true
console.log("hello" == "Hello") // false
console.log(undefined == null) // true
console.log(12 == 10) // false
console.log(12 == '10') // false
console.log(undefined == false) // false
'==
' operator is helpful when we don't care about the operands' data types and only want to compare their values.
===
operator
===
operator is the symbol that shows the strict equality operator. It also compares the operands on either side of it but it is slightly different from the equality operator.
It doesn't perform the type coercion of the operands. It just reads the two operands and if both of them have the same value as well as the same data type, then only it will return true
, otherwise, it will return false
.
console.log('100' === 100) // false
console.log(100 === 100) // true
console.log("Hello" === "Hello") // true
console.log(1 === true) // false
console.log('false' === false) // false
console.log(true === true) // true
When '100',
which is a string, is compared with 100
, which is a number, using the '===
' operator, it returns false
because it doesn't convert the data types of the operands and checks if both the operands have the same values and the same data types.
Also, 1
is a number and true
is a boolean value, so it returns false.
Since it produces predictable results, we should primarily use the strict equality operator(===
). Using this won't lead to unexpected outcomes.
Conclusion
We can infer from the discussion of the two types of equality operators above that the strict equality operator (===
) does not convert the data type and only returns true
if the data type and value of the operands are equal. In contrast, the loose equality operator (==
) converts the data type of the operands before comparing their values. The single and most fundamental distinction between the equality operators is this.