0%

javascript-operator-or

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
2
3
4
5
6
x || y // return x if x is truthy, otherwise return y
x || y || z // return the first truthy value among x, y, z, or z if all operands are falsy values.
// examples
1 || 2 // 1
0 || 1 // 1
0 || "" || 1 // 1

|| can return non-boolean values

Logical operator or || in most programming languages only return boolean values, but in JavaScript, this is not true.

1
2
3
4
1 || 2 // 1, number type
"hello" || "world" // "hello", string type
0 || null // null, null type
0 || undefined // undefined, undefined 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
2
3
4
function makeRequest(url, timeout, callback) {
timeout = timeout || 2000;
callback = callback || function() {};
}

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
2
3
makeRequest("https://example.com", 0, function() {
console.log("done");
});

To fix this, we can explicitly check whether the arguments is undefined.

1
2
3
4
function makeRequest(url, timeout, callback) {
timeout = (timeout !== undefined) ? timeout : 2000;
callback = (callback !== undefined) ? callback : function() {};
}

Or use the nullish operator ??, which only returns the right-hand side value if the left-hand side value is null or undefined.

1
2
3
4
function makeRequest(url, timeout, callback) {
timeout = timeout ?? 2000;
callback = callback ?? function() {};
}

Short-circuit evaluation

The logical OR expression is evaluated left to right, it will stop evaluating once it finds a truthy value.

1
2
3
4
5
6
7
8
9
10
function A() {
console.log("called A");
return false;
}
function B() {
console.log("called B");
return true;
}

console.log(B() || A());

The code above will output:

  1. called B
  2. 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