April 9, 2020
Estimated Post Reading Time ~

Equality(==) vs Identity(===)

In JavaScript, we have Equality (==) and Identity(===) operators for equality comparison between two values/operands. When the first time we see Equality (==) and Identity (===) operators, the following questions arise in our mind.
1. What is the difference between Equality (==) and Identity (===)?
2. Is there a performance benefit with Equality (==) or Identity (===)?

Answers:
1. What is the Difference Between Equality (==) And Identity (===)?
Equality (==) returns true if both value/operands have the same value, without worrying about the type of both value/operands.
e.g.
  • 2 == 1 // returns false, both value/operands have different value.
  • 2 == 2 // returns true, both value/operands have same type and value
  • 2 == "2" // returns true, while both value/operands have different type, first value is type of number and second one is type of string, but value is same.
Equality (==) first compares types, if types are not same, then first convert both values/operands to the same type, then compare both value/operands, while on other hand Identity (===) first compares types, if types are same then it only compares the value of both the operands, otherwise returns false.
e.g.
  • 2 === 1 // returns false, both value/operands have different value.
  • 2 === 2 // returns true, both value/operands have same type and value
  • 2 === "2" // returns false, both value/operands have same value but different types, first value is type of number and second one is string.
2. Is there a performance benefit with Equality (==) or Identity (===)?
Identity (===) does not do type conversion (if types are not the same it returns false), So Identity (===) is faster than Equality (==).

NOTE: Identity (===), is generally better and safer because there is no behind the scenes type conversion.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.