JavaScript 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.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

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

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours