JavaScript Nullish Coalescing
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 (nullorundefined).value2: The second operand that acts as the default value, returned only ifvalue1is 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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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