Nullish coalescing operator
The ?? operator, or nullish coalescing (null-coalescing operator), is a modern way to set a default value, but only when a variable equals null or undefined, not any "falsy" value.
Syntax
a ?? bIt reads as:
"If
ais notnulland notundefined, returna; otherwise, returnb."
Example
const name = null;
const displayName = name ?? 'Guest';
console.log(displayName); // "Guest"Here name is null, so 'Guest' is returned.
Comparison with || (logical OR)
They are similar, but there is an important difference: || treats all falsy values (0, '', false, NaN, null, undefined) as "false", while ?? reacts only to null and undefined.
Comparison example:
const a = 0;
console.log(a || 100); // 100, because 0 is falsy
console.log(a ?? 100); // 0, because 0 is not null/undefinedSo
??preserves values like0,false,''.
Comparison table
Value a | a || 'default' | a ?? 'default' |
|---|---|---|
undefined | 'default' | 'default' |
null | 'default' | 'default' |
0 | 'default' | 0 |
false | 'default' | false |
'' | 'default' | '' |
'text' | 'text' | 'text' |
Example with an object
const settings = {
theme: null,
notifications: false,
};
const theme = settings.theme ?? 'light';
const notifications = settings.notifications ?? true;
console.log(theme); // "light"
console.log(notifications); // false (not replaced!)
notificationswas not replaced withtrue, becausefalseis notnulland notundefined.
Example in functions
function greet(name) {
const user = name ?? 'Guest';
console.log(`Hello, ${user}!`);
}
greet('Oleh'); // "Hello, Oleh!"
greet(null); // "Hello, Guest!"
greet(); // "Hello, Guest!"Combining with && and ||
You can combine them, but you need to use parentheses to avoid precedence errors:
const result = (a ?? b) && c;Without parentheses, an error may occur in strict mode:
javascriptSyntaxError: Unexpected token '&&'
Example in a real situation
Setting a default value
const page = config.page ?? 1;Validating data from an API
const userName = response.data.name ?? 'Anonymous';Displaying in the interface
console.log(`Hello, ${user.name ?? 'guest'}!`);Summary
| Characteristic | Operator ?? | Operator || |
|----------------|----------------|----------------|
| Checks | only null and undefined | all falsy values (0, '', false, NaN, null, undefined) |
| Returns | the first "non-nullish" value | the first "truthy" value |
| Used for | default values | logical checks |
In short
value1 ?? value2
// if value1 !== null && value1 !== undefined -> return value1
// otherwise -> return value2Examples of the ?? operator:
null ?? 'default' // "default"
undefined ?? 'default' // "default"
0 ?? 100 // 0
'' ?? 'text' // ""
false ?? true // falseShort Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.