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 | true || true; // t || t returns true |
||
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 | "" || 1; // returns 1 |
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 | const x = 0; |