Logical Operators

    The main logical operators are:

    • && - and
    • || - or
    • ! - not

    These automatically coerce types, which is idiomatic to do, despite being somewhat confusing.

    Truthiness

    When using logical operators, the operands will be coerced to booleans before being compared.

    Values coerced to true are called truthy values; all other values are falsy values. The falsy values:

    TypeValue
    Booleanfalse
    Number and BigInt0, -0, 0n, -0n, NaN
    String""
    Othernull, undefined

    A truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. (Definition: mdn).

    Not Operator

    We use ! to convert a truthy value to false, or a falsy value to true.

    And Operator

    The && operator takes two operands:

    • If the first operand is falsy, it evaluates to the first operand
    • If the first operand is truthy, and it evaluates to the second operand

    Or Operator

    The || operator takes two operands:

    • If the first operand is truthy, it evaluates to the first operand
    • If the first operand is false, and it evaluates to the second operand

    Short Circuiting

    Both && and || are short-circuiting operators:

    • &&: if the first operand is evaluated as falsy, the second operand will not be evaluated at all (i.e. side-effects will not occur)
    • ||: if the first operand is evaluated as truthy, the second operand will not be evaluated at all