JavaScript Nullish Coalescing(??) Operator
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. It's commonly used to provide default values for variables.
Syntax:
variable ?? default_value
Below are examples of the Nullish Coalescing Operator.
Example 1: In this example, we will see a basic function using the nullish coalescing operator
function foo(bar) {
bar = bar ?? 55;
console.log(bar);
}
foo(); // 55
foo(22); // 22
Output
55 22
Example 2: The more common use case is to set default values for JSON objects as follows.
const foo = {
bar: 0
}
const valueBar = foo.bar ?? 42;
const valueBaz = foo.baz ?? 42;
// Value of bar: 0
console.log("Value of bar: ", valueBar);
// Value of bar: 42
console.log("Value of baz: ", valueBaz);
Output
Value of bar: 0 Value of baz: 42
Supported Browsers: The browsers supported by JavaScript Nullish Coalescing Operator are listed below: