0%

javascript-logical-or-operator

How logical or || operator works in JavaScript

Consider the following expression, what’s the evaluated result?

1
`expr1 || expr2`

If expr1 can be converted to true, return expr1. Otherwise, return expr2.
So we have the following truth:

1
2
3
4
5
6
7
8
9
10
true || true; // t || t returns true
false || true; // f || t returns true
true || false; // t || f returns true
false || 3 === 4; // f || f returns false
"Cat" || "Dog"; // t || t returns "Cat"
false || "Cat"; // f || t returns "Cat"
"Cat" || false; // t || f returns "Cat"
"" || false; // f || f returns false
false || ""; // f || f returns ""
false || varObject; // f || object returns varObject

|| in javascript not always return boolean(true or false)

Note that || in javascript is quit difference from || in other languages. For example, in Java, || returns Boolean(true or false), but in JavaScript, it returns the value of one of the operands.

1
2
"" || 1; // returns 1
false || ""; // returns ""

If you want to convert the value to boolean, you can use double !! or Boolean()

  • !!expr - convert to boolean
  • Boolean(expr) - convert to boolean

Short circuit

|| is a short-circuit operator, which means if the first operand is true, it will not evaluate the second operand.

1
true || console.log("Hello"); // nothing output

|| vs ??

|| and ?? are both used to provide a default value, but they have different behaviors, if you only care about null or undefined, and treat other Falsy value as valid(for example 0 or empty string "") use ??, otherwise, use ||.

1
2
3
4
5
6
7
const x = 0;
const y = x || 10; // y = 10
const z = x ?? 10; // z = 0

const a = "";
const b = a || "default"; // b = "default"
const c = a ?? "default"; // c = ""

References

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment