Home Cryptocurency ExchangesEquality (==) vs. Identity (===) Operators
Equality (==) vs. Identity (===) Operators

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 !!

Source

Leave a Reply

Your email address will not be published. Required fields are marked *

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.