What is the difference between == and === in JS?

Intro Line

In JavaScript, \=\= and \=\=\= are operators used for comparison, but they differ in how they compare values.

3 points of comparison

Type Coercion

  • \=\=: Performs type coercion, which means it converts the values to a common type before making the comparison.
  • \=\=\=: Does not perform type coercion. It checks for both value and type equality, so the values must be of the same type to be considered equal.

Strictness

  • \=\=: Known as the loose or abstract equality operator. It's less strict, as it allows for an equality comparison of values after type conversion.
  • \=\=\=: Known as the strict equality operator. It's stricter as it requires both values to be of the same type for equality.

Real-world Usage

  • In real-world coding, \=\=\= is generally preferred for comparisons to avoid unintended results due to type coercion by \=\=. For example, when validating inputs or comparing values fetched from a database or API, \=\=\= ensures that you're comparing both the value and the type, reducing the risk of bugs.

Examples:

  • [] == [] // false
  • var arr1 = []; var arr2 = []; console.log(arr1 == arr2); // false

Explanation:

  • In JavaScript, the equality operator (==) compares objects by reference, not by value. When comparing two arrays with [] == [], two separate array objects are being compared. Since each array object has its own unique reference in memory, the comparison evaluates to false. Even though the arrays have the same contents (i.e., both are empty), they are distinct objects and occupy different memory locations. Therefore, the comparison [] == [] returns false.