Nullish Coalescing in JavaScript: What It Is and How It Works
nullish coalescing operator (??) in JavaScript returns the right-hand value only if the left-hand value is null or undefined. It helps provide default values without treating other falsy values like 0 or '' as empty.How It Works
Think of the nullish coalescing operator ?? as a smart helper that checks if a value is truly missing or empty in a special way. It only considers null or undefined as missing, unlike other operators that treat many values like 0, false, or empty strings as empty.
Imagine you ask a friend for their phone number. If they say "I don't have one" (which is like null or undefined), you use a backup number. But if they say "0" or "" (empty), you accept that as their real answer. This is how ?? works—it only switches to the backup if the first answer is truly missing.
Example
This example shows how ?? returns the left value unless it is null or undefined, then it returns the right value as a default.
const value1 = 0 ?? 42; const value2 = null ?? 42; const value3 = undefined ?? 42; const value4 = '' ?? 'default'; console.log(value1); // 0 console.log(value2); // 42 console.log(value3); // 42 console.log(value4); // ''
When to Use
Use nullish coalescing when you want to provide a default value only if a variable is null or undefined, but keep other valid falsy values like 0, false, or empty strings intact.
For example, when reading user input or configuration settings, you might want to accept 0 or false as valid inputs and only replace missing values with defaults. This avoids bugs where || would wrongly replace these falsy but valid values.
Key Points
??only checks fornullorundefined.- It preserves other falsy values like
0,false, and empty strings. - It helps avoid unintended defaulting when using
||. - It is useful for setting default values safely.
Key Takeaways
?? to provide defaults only when a value is null or undefined.?? keeps valid falsy values like 0, false, and '' unchanged.|| treating all falsy values as empty.