techStackGuru

Difference between “ == “ and “ === “ operators


To compare objects in JavaScript, the operators === and == are used. The distinction between the two operators is that while "==" compares values, "===" compares both values and types. It is also know as loose equality (==) and strict equality (===) operators.

Strict Equality (===):

  • === checks for equality without converting types.
  • When the operands have the same type and value, it returns true.
  • When the operands differ in type or value, it returns false.
  • Example

    console.log(5 === 5);        // true
    console.log("5" === 5);      // false (different types)
    console.log(5 === "5");      // false (different types)
    console.log(true === true);  // true
    console.log(null === undefined); // false (different types) 

    Loose Equality (==):

  • == checks equality with type coercion.
  • The type conversion allows comparison between different types.
  • When the operands are equal after conversion, it returns true.
  • When the operands are not of the same type or cannot be converted, it returns false.
  • Example

    console.log(5 == 5);        // true
    console.log("5" == 5);      // true (converted string to number)
    console.log(5 == "5");      // true (converted string to number)
    console.log(true == 1);     // true (converted boolean to number)
    console.log(null == undefined); // true (special case) 

    With ===, you check both value and type equality explicitly, which is considered safer and less likely to lead to unexpected behavior. In contrast, == allows for greater flexibility because type coercion is performed, which can sometimes lead to unexpected outcomes.