How does comparison work in Javascript

In Javascript we can use == and === to compare two variables

1. Compare Reference Type

If 2 objects have different reference. == or === will both return false


2. Strict equality using ===

It will compare 2 variables without doing any conversion

  • If both operands have different types, they are not strictly equal
  • null === null -> true
  • undefined === undefined -> true
  • NaN === NaN -> false
  • true === true (or false === false) -> true
  • If both operands are both numbers or string and have the same value, they are strictly equal
  • Reference type have to point to the same memory location to be strictly equal
  • In all other cases operands are not strictly equal


3. Equality Operator using ==

If the operands have the same type, just like ===

If the operands have different type. It will do some conversion before comparison

  • null == undefined -> true
  • If one operand is number and another is a string, convert the string to number. Compute the comparison again
  • If one operand is boolean, transform true -> 1 and false -> 0. Compute the comparison again
    • true == 1 -> true
    • true == "1" -> true (Because true -> 1 and "1" also -> 1)
    • true == 2 -> false
  • If one operand is an object and another is a number or string, convert the object to a primitive using OPCA. Compute the comparison again
  • In all other cases operands are not equal