Fly with code

Get wet inside ocean of code

0%

Truthy & Falsy vs Logical operators

Truthy

  • A value that is considered true when encountered in a Boolean context.
  • All values are truthy unless they are defined as falsy.

Falsy

  • false, 0, -0, 0n, "", null, undefined, and NaN.

Logical operators

  • AND (&&)
    For expr1 && expr2, returns expr1 if it can be converted to false; otherwise, returns expr2

  • OR (||)
    For expr1 && expr2, returns expr1 if it can be converted to true; otherwise, returns expr2.

  • NOT (!)
    For !expr, returns false if its single operand that can be converted to true; otherwise, returns true.

Example 1

1
2
3
4
5
console.log(0 && 1); // 0
expr1 is 0,which is falsy, then return expr1

console.log(1 && 0); // 0
expr1 is 1, which is truthy, then return expr2

Example 2

1
2
3
4
5
console.log(0 || 1); // 1
expr1 is 0, which is falsy, then return expr2

console.log(1 || 0); // 1
expr1 is truthy, which is truthy, then return expr1

Example 3

1
2
3
4
5
6
7
let a=1;
let b=2;
let c=0;
console.log(a && b && c); // 0

Associativity of && is left-to-right
count a && b first, return b, then count b && c, return c, which is 0.

Example 4

1
2
3
4
5
6
7
8
9
10
let a=1;
let b=2;
let c=0;
console.log(c || c && c || a); //1

Precedence of && is 6, and Precedence of || is 5.
Therefore, it will count c && c first, then return c.
then, it will become console.log(c || c || a).
Associativity of || is left-to-right
Count c || c first, return c, then count c || a, return a, which is 1.

Additional Knowledge

Logical operators
JavaScript-Equality-Table