The main logical operators are:
These automatically coerce types, which is idiomatic to do, despite being somewhat confusing.
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:
|Number and BigInt|
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).
! to convert a truthy value to
false, or a falsy value to
&& 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
|| 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
|| 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