Javascript Equality Check

ikbalarslan

ikbal arslan

Posted on May 27, 2024

Javascript Equality Check

In javascript equality sign= is used for assigning variables so we use something different to check equality.

In javascript, we have three ways to check equality:

  • double equals ==
  • triple equals ===
  • Object.is()

== (double equals)

Double equals will allow coercion
this is the algorithm for double equals:
1 - if types are the same do the rest of the calculations with triple equals
2 - null and undefined are equal to each other.
3 - if any side is reference type call ToPrimitive()
4 - if we have two different primitive types convert both of them to numbers then do the equality check.

Since double equals allow coercion it allows some corner cases as well

for example

[] == ![] // true
Enter fullscreen mode Exit fullscreen mode

For not dealing with corner cases we shouldn't use these with double equals:

  • don't use 0,"", " "
  • don't use reference types
  • don't compare with a boolean

If the types are equal it will send it to triple equals anyway

=== (triple equals)

It doesn't allow coercion. first, it checks the types if the types are equal it will check values then it will check equality.

1 === "1" //Since the types are not equal its false
Enter fullscreen mode Exit fullscreen mode

Object.is()

It behaves the same as the triple-equals operator except NaN and +0 and -0.



1 === 1; // true
Object.is(1, 1); // true

+0 === -0; // true
Object.is(+0, -0); // false

NaN === NaN; // false
Object.is(NaN, NaN); // true
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ikbalarslan
ikbal arslan

Posted on May 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related