Nullish coalescing
- Node.js course
- Beginner
- Lesson 28/116
- 5 min
Learn nullish coalescing with ?? and optional chaining.
Nullish coalescing
The nullish coalescing operator ?? returns the right side if the left side is null or undefined; otherwise it returns the left side.
For example, userInput ?? 'guest'. If userInput is null, the result is 'guest'; otherwise it is the value of userInput.
This is ideal for assigning default values. The difference from ||: || also catches falsy values (0, '', false); ?? only catches null/undefined.
Optional chaining
The optional chaining operator is written with ?. and provides safe access to an object's property. If the property does not exist, it returns undefined instead of throwing an error.
For example, user?.name. If user is null or undefined, the result is undefined; no error is thrown.
This is very useful for nested objects: order?.customer?.address?.city. If any intermediate step is missing, the chain stops safely.
Practice Default value with ??
Declare userInput = null and defaultValue = 'guest'. Compute name as userInput ?? defaultValue. Call console.log(name).
Starter code
const userInput = null;
const defaultValue = "guest";
// Compute name as userInput ?? defaultValue
// Log it with console.logSample solution
const userInput = null;
const defaultValue = "guest";
const name = userInput ?? defaultValue;
console.log(name);Expected output
guest
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match Nullish vs OR
| Term | Meaning |
|---|---|
?? |
Nullish coalescing |
|| |
Logical or |
?. |
Optional chaining |
&& |
Logical and |
2 What does the ?? operator do?
- Divides two numbers
- Returns the right side if the left is null/undefined Correct answer
- Returns the right side if the left is false
- Concatenates two strings
Explanation: ?? returns the right side if the left is null/undefined.
3 ?? example
const name = userInput ____ 'guest';
const name = userInput ?? 'guest';
Explanation: ?? returns the right side if the left is null/undefined.