DEV Community

Cover image for "==" or "===" ? Key difference b/w them
SYED MAZHAR ALI RAZA
SYED MAZHAR ALI RAZA

Posted on

"==" or "===" ? Key difference b/w them

While learning JS, I've always wondered how == and === are different from each other, and how exactly do they work BTS. So here's what I got to know.

The equality operator (==) uses the Abstract Equality Comparison Algorithm to compare two operands. In simple words, it compares the two operands irrespective of their datatypes. For example:

console.log(2 == "2") will return true, even if the second operand here is a string. But why? How? Here's the deal.

When the operands are of different types, the algorithm converts the operands to the same datatype before comparing. Now, which one gets converted, you may ask.

  • On comparing a number with a string, the string is converted to a number. (empty string is converted to 0, non-number strings return NaN i.e Not a Number)
  • If either of the operands is a boolean, it gets converted to either number 1(if true) or 0(if false).
  • Lastly, if one of the operands is an object and the other is a number or a string, the object gets converted to a primitive value (just like using valueOf() and toString() methods)

The strict equality operator (===) uses the Strict Equality Comparison Algorithm to compare two operands. Even "===" also checks whether two values are the same or not but there is no type conversion before comparison. So even if the values of two operands are the same, but are of different datatypes, it will return false.

Happy coding :)

10DaysofJSFundamentals (DAY 3)

Top comments (0)