The nullish coalescing (??) operator is used to handle null and undefined values in JavaScript. It allows you to assign a default value when a variable does not have a valid value.
- It returns the right-hand value only when the left-hand value is null or undefined.
- It does not treat 0, false, or empty strings as nullish values.
- It is useful for setting safe default values without overwriting valid data.
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
Syntax:
variable ?? default_valueExample 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);
Best Practices
- Use ?? when you only want to handle null or undefined.
- Avoid mixing ?? with || in the same expression without parentheses.
- Prefer ?? for default values in configuration and API responses.
Supported Browsers: The browsers supported by JavaScript Nullish Coalescing Operator are listed below: