If you have worked on javascript then you must have noticed these two operators to compare values. Many developers do not understand the correct version they use in specific scenarios. The correct decision is based on knowledge that how actually they work? Let’s understand.
Remember when performing comparisons, the equality operator (==
) will attempt to make the data types the same before proceeding. On the other hand, the identity operator (===
) requires both data types to be the same, as a prerequisite.
Let’s understand with an example. See the code below :
var valueOne = 3; var valueTwo = "3"; if (valueOne == valueTwo) { console.log("ValueOne and ValueTwo are the same"); } else { console.log("ValueOne and ValueTwo are NOT the same"); }
Can you guess the output? You may or may not be surprised, but these values are considered to be the same.
Output is: ValueOne and ValueTwo are the same
The reason why the ==
operator reasons that "3"
and 3
are the same is because it actually coverts the operands (the values either side of the ==
operator) to the same type before it does the comparison.
However, if we change the operator to an identity operator, as shown here, we see quite different output:
var valueOne = 3; var valueTwo = "3"; if (valueOne === valueTwo) { console.log("ValueOne and ValueTwo are the same"); } else { console.log("ValueOne and ValueTwo are NOT the same"); }
Now with identity operator, output is:
Output is: ValueOne and ValueTwo are NOT the same
Since we used the ===
operator on this occasion, and because this operator does not do any type conversion, we see that the string value "3"
and the number 3
are not the same after all.
Happy Learning !!