Sobes.tech
Junior

What happens in JavaScript during a loose equality comparison (==)?

sobes.tech AI

Answer from AI

In loose comparison (==) in JavaScript, type coercion of operands occurs before comparison. If operand types differ, JavaScript attempts to convert one or both operands to a common type based on a set of rules.

Main rules for coercion with ==:

  1. Number and String: The string is converted to a number. If conversion fails (NaN), the result is always false.
    // "10" converts to 10. Result: true
    console.log(10 == "10");
    // "abc" converts to NaN. Result: false
    console.log(10 == "abc");
    
  2. Boolean and Non-Boolean: Boolean is converted to a number (true to 1, false to 0). Then, the number is compared to the other operand (which may be converted).
    // true converts to 1. Result: true
    console.log(true == 1);
    // false converts to 0. Result: true
    console.log(false == 0);
    // false converts to 0, "0" converts to 0. Result: true
    console.log(false == "0");
    
  3. Null and Undefined: null compares equal to undefined as true, and not equal to anything else (except itself).
    // Result: true
    console.log(null == undefined);
    // Result: false
    console.log(null == 0);
    // Result: false
    console.log(undefined == 0);
    
  4. Object and Primitive: The object is converted to a primitive (using valueOf or toString), then primitives are compared.
    // Object converts to string "10" (via toString()), then compared to number 10
    // "10" converts to 10. Result: true
    console.log({ toString: () => "10" } == 10);
    
  5. Symbol and Other: Symbols can only be compared with other symbols or primitive values to which the symbol can be converted (which is generally not possible in standard cases).
    // Result: false
    console.log(Symbol('a') == 'a');
    

Loose comparison can lead to unexpected results due to automatic type coercion. For more predictable behavior, it is recommended to use strict comparison (===), which does not perform type coercion and compares operands directly.