JavaScript – Equality (==) vs. Identity (===) Operators

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.

When in doubt, a relatively safe choice is simply to use the identity operator (===) as a matter of habit. Of course, the safest choice is to familiarize yourself with the differences, so that you know what is actually happening under the hood.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “JavaScript – Equality (==) vs. Identity (===) Operators”

  1. Why should we override the hashCode() and equals methods in POJO Class when we use Hash based Collection ? Why cannot it work on System generated hashCode() instead of overrided hashCode() ?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.