Nullish Coalescing

hitomipupil's avatar
Published Jan 8, 2025
Contribute to Docs

In JavaScript, the nullish coalescing (??) operator is a logical operator that evaluates the left-hand operand and returns it if it is not nullish (i.e., not null or undefined). Otherwise, it returns the right-hand operand.

Syntax

value1 ?? value2
  • value1: The first operand to check if it is nullish (null or undefined).
  • value2: The second operand that acts as the default value, returned only if value1 is nullish.

Example

The following example demonstrates the use of the nullish coalescing operator to return 18 as a default or fallback value when the variable age is null or undefined:

const age = undefined;
const defaultAge = 18;
console.log(age ?? defaultAge);

The above code produces the following output:

18

Codebyte Example

The following codebyte example uses the nullish coalescing operator (??) to return "Guest" as a fallback value when name is null:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy