JavaScript Logical operators


Logical operators in JavaScript are used to combine multiple boolean expressions or values and return a boolean result. They are essential for controlling the flow of your program based on complex conditions. Here’s an overview of the main logical operators:

1. Logical AND (&&)

  • Purpose: Returns true if both operands are true; otherwise, returns false.

  • Short-circuit Evaluation: If the first operand is false, JavaScript doesn’t evaluate the second operand.

  • Example:

    let a = true; let b = false; console.log(a && b); // false, because b is false
    let x = 10; let y = 20; console.log(x > 5 && y < 25); // true, both conditions are true

2. Logical OR (||)

  • Purpose: Returns true if at least one of the operands is true; otherwise, returns false.

  • Short-circuit Evaluation: If the first operand is true, JavaScript doesn’t evaluate the second operand.

  • Example:

    let a = true; let b = false; console.log(a || b); // true, because a is true
    let x = 10; let y = 30; console.log(x < 5 || y > 25); // true, because y > 25 is true

3. Logical NOT (!)

  • Purpose: Inverts the boolean value of its operand. Returns true if the operand is false, and false if the operand is true.

  • Example:

    let a = true; console.log(!a); // false, because a is true
    let b = false; console.log(!b); // true, because b is false

4. Logical AND (Short-circuit)

  • Purpose: Evaluates from left to right, stopping as soon as it encounters a false value. Useful for conditional execution.
  • Example:
    let a = null; let b = 'Hello'; console.log(a && b); // null, because a is falsy

5. Logical OR (Short-circuit)

  • Purpose: Evaluates from left to right, stopping as soon as it encounters a true value. Useful for default values.
  • Example:
    let a = 'Hello'; let b = 'World'; console.log(a || b); // 'Hello', because a is truthy

Key Points:

  • Short-circuiting: Logical operators use short-circuit evaluation to optimize performance. This means that if the result can be determined by the first operand, the second operand is not evaluated.
  • Falsy Values: In JavaScript, values like 0, NaN, null, undefined, '' (empty string), and false are considered falsy. All other values are considered truthy.
  • Type Coercion: Logical operators work with boolean values but can also coerce other types into boolean values. For instance, in the expression 0 || 'fallback', 0 is falsy, so 'fallback' is returned.