Skip to main content

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

javascript
a ?? b

It reads as:

"If a is not null and not undefined, return a; otherwise, return b."


Example

javascript
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:

javascript
const a = 0; console.log(a || 100); // 100, because 0 is falsy console.log(a ?? 100); // 0, because 0 is not null/undefined

So ?? preserves values like 0, false, ''.


Comparison table

Value aa || 'default'a ?? 'default'
undefined'default''default'
null'default''default'
0'default'0
false'default'false
'''default'''
'text''text''text'

Example with an object

javascript
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!)

notifications was not replaced with true, because false is not null and not undefined.


Example in functions

javascript
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:

javascript
const result = (a ?? b) && c;

Without parentheses, an error may occur in strict mode:

javascript
SyntaxError: Unexpected token '&&'

Example in a real situation

Setting a default value

javascript
const page = config.page ?? 1;

Validating data from an API

javascript
const userName = response.data.name ?? 'Anonymous';

Displaying in the interface

javascript
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

javascript
value1 ?? value2 // if value1 !== null && value1 !== undefined -> return value1 // otherwise -> return value2

Examples of the ?? operator:

javascript
null ?? 'default' // "default" undefined ?? 'default' // "default" 0 ?? 100 // 0 '' ?? 'text' // "" false ?? true // false

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.