Introduction to javascript operator ||
In JavaScript, the ||
operator is used to return the first truthy value among its operands. If all operands are falsy values, it returns the last operand.
1 | x || y // return x if x is truthy, otherwise return y |
||
can return non-boolean values
Logical operator or ||
in most programming languages only return boolean values, but in JavaScript, this is not true.
1 | 1 || 2 // 1, number type |
arguments checking
||
is often used to check if an argument is provided or not. If the argument is not provided, a default value will be used.
1 | function makeRequest(url, timeout, callback) { |
In above example, if timeout
or callback
is not provided, the default value will be used.
But there is a problem with this approach, if the argument is provided but falsy value(for example, pass 0 for timeout), the default value will be used. In the following code, we intend to use 0 as the timeout value, but 0 || 2000 = 2000
, so 2000
was used as the timeout value.
1 | makeRequest("https://example.com", 0, function() { |
To fix this, we can explicitly check whether the arguments is undefined.
1 | function makeRequest(url, timeout, callback) { |
Or use the nullish operator ??
, which only returns the right-hand side value if the left-hand side value is null
or undefined
.
1 | function makeRequest(url, timeout, callback) { |
Short-circuit evaluation
The logical OR expression is evaluated left to right, it will stop evaluating once it finds a truthy value.
1 | function A() { |
The code above will output:
- called B
- true
In the above example, B()
is called first, and it returns true
, so A()
is not called.
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR