JavaScript-primer

Equality and Type

Loose Equality

The most basic equality operator in JavaScript using ==. Loose equality compares values regardless of types following these steps:

  1. If both values are either null or undefined, return true.
  2. Convert all booleans to numbers. True converts to 1 and false converts to 0.
  3. If comparing a number to a string, convert the string to a number.
  4. If comparing an object to a string, convert the object using its toString() or valueOf() methods.
  5. If the types are the same, follow the same rules as strict equality.

In general, strict equality should be preferred due to it being easier to predict. However, loose equality can be useful for checking against null and undefined at once with value == null.

Learn more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality

Strict Equality

A JavaScript equality operator using ===. Strict equality compares both values and types following these steps:

  1. If either value is NaN, return false.
  2. If the values have different types, return false.
  3. If both values are null or both values are undefined, return true.
  4. If both values are objects, return true if they are the same object. False otherwise.
  5. If both values are of the same primitive type, return true if the values are the same. False otherwise.

Learn more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality