Comparison operators in JS

Abhay Jain
2 min readDec 18, 2020

--

JavaScript provides 3 different comparison operators.

  • == operator
  • === operator
  • Object.is()

== or Abstract equality operator

Double equals or Loose equality operator which checks if only the values are equal and then returns true. In this case, if the type of the expressions is different, the expressions are converted to one common type using implicit typecasting.

Cheat Sheet for you while using == operator

  • NaN is not equal to anything including itself
  • -0 equals 0
  • null equals both null & undefined
  • The expressions are either converted to a string, boolean, or number.
  • String comparison is case sensitive
  • If the two operands refer to the same object then it evaluates to true otherwise false
  • Always remember 6 falsy values (null, undefined, ‘’,0, NaN, and false)

=== or Strict equality operator

Triple equals or Identity operator is very similar to Double equals operator except it doesn’t do any implicit typecasting. This operator returns true if both the value and the type of the left & right side expressions are equal.

Cheat Sheet for you while using === operator

  • -0 equals 0
  • null only equals null
  • String comparison is case sensitive
  • NaN is not equal to anything including itself
  • If the two operands refer to the same object then it evaluates to true otherwise it returns false

Object.is()

Same-value equality operator is the newest addition to comparison operators (available from ES2015). It checks if the two values are the same using the following rules.

Rule 1: Both values are undefined.

Rule 2: Both values are strings of the same length, with the same characters in the same order.

Rule 3: Both values are null.

Rule 4: Both values are objects having the same reference.

Rule 5: Both values are the same non-zero and non-NaN number.

Rule 6: Both values are either +0 or -0.

Rule 7: Both NaN.

Array.prototype.indexOf() uses Strict Equality Operator or ===.

--

--

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.