The OR operator (double pipe) || uses the right value if the left is falsy, while the nullish coalescing operator ??
(double question mark) uses the right value if the left is null
or undefined
.
These operators are often used to provide a default value if the first one is missing.
Double Question Mark (??
):
The double question mark is known as the “nullish coalescing operator” and was introduced in ECMAScript 2020 (ES11). It is used to provide a default value when a variable is null
or undefined
.
const result = someValue ?? defaultValue;
The ??
operator checks if someValue
is null
or undefined
. If it is, the defaultValue
is returned; otherwise, the value of someValue
is returned.
Double Pipe (||
):
The double pipe is the “logical OR operator” and has been a part of JavaScript for a long time. It is primarily used for boolean expressions and short-circuit evaluation. When used in a logical expression, it returns the first truthy operand (not necessarily a boolean true
) or the last operand if all the operands are falsy.
const result = operand1 || operand2;
In this context, operand1
and operand2
are expressions or values that you want to evaluate. The ||
operator performs a logical OR operation on these operands and returns the value of the first truthy operand, or the last operand if all operands are falsy.
JavaScript double question mark vs double pipe
A simple example code is the OR operator ||
can be problematic if your left value might contain ""
or 0
or false
(because these are falsy values):
console.log(12 || "not found") // 12
console.log(0 || "not found") // "not found"
console.log("jane" || "not found") // "jane"
console.log("" || "not found") // "not found"
console.log(true || "not found") // true
console.log(false || "not found") // "not found"
console.log(undefined || "not found") // "not found"
console.log(null || "not found") // "not found"
Output:
In many cases, you might only want the right value if left is null
or undefined
. That’s what the nullish coalescing operator ??
is for:
console.log(12 ?? "not found") // 12
console.log(0 ?? "not found") // 0
console.log("jane" ?? "not found") // "jane"
console.log("" ?? "not found") // ""
console.log(true ?? "not found") // true
console.log(false ?? "not found") // false
console.log(undefined ?? "not found") // "not found"
console.log(null ?? "not found") // "not found"
As a very short rule, you could look at it the opposite way:
||
(or)returns the first "truthy" value
(or the last value if no “truthy” value exists)??
(nullish coalescing)returns the first "defined" value
(or the last value if no “defined” value exists)
Example
x = false || true; // --> true (the first 'truthy' value - parameter 2)
x = false ?? true; // --> false (the first 'defined' value - parameter 1)
Source: stackoverflow.com
Do comment if you have any doubts or suggestions on this JS code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version