Introduction
In any programming language, we will often find that comparing two values with each other is one of the most common codes written. In Javascript, one way of comparing two values is using the "===" Triple Equal Operator and "==" Double Equals operator. Let's have a look at these operators and how they differ from each other or let's witness the equality war and see who wins!
Triple Equality Operator "==="
Triple equality operator "===" is also referred to as strict equality. It returns a boolean value i.e. true
or false
on the comparison of two operands as well as the type of the operands that are compared.
console.log("antman" === "antman")
//true
console.log("ironman" === "antman")
//false
In the above example, we can see that if the values and type on either side of the "===" are equal then we get the result as true
or else we get false
.
Let's see another example now.
console.log("30" === 30)
//false
console.log(30 ===30)
//true
In the first example, the left operand is a string "30" while the right operand 30 is a number.
Even though the values are the same, we can notice that the types of both operands are different. Referring to its name, the triple equality operator strictly compares the types and values and returns the result accordingly.
Double Equality Operator "=="
Double equality operator "==" is also referred to as loose equality. It returns a boolean value i.e. true
or false
on comparison of only the values of two operands.
console.log("antman" == "antman")
//true
console.log("ironman" == "antman")
//false
In the above example, we can see that if the values on either side of the "==" are equal then we get the result as true
or else we get false
But here comes the fun part...
"==" does an additional task while comparing.
It does Type coercion.
Nothing to work about this big fancy word, Type coercion is just the automatic or implicit conversion of values from one data type to another. Let's look at the same example we used while learning the triple equality operator.
console.log(30 == "30")
//true
The double equality operator does the type coercion of a string to a number and outputs the result. Hence, even though the types of both operands are not the same, we get the result as true
.
Conclusion
The usage of "==" vs "===" depends upon the use case of the code, but in most of the cases Triple equality operator is preferred since it helps to evaluate the type of the operands and does not convert it implicitly like the Double equality operator "==".
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion