Lesson 19: Mastering JavaScript Nullish coalescing operator (??) with challenges!

✅ What is ??
?
The nullish coalescing operator (??
) returns the first defined value among its operands.
A value is considered "defined" if it’s not null
and not undefined
.
✅ Syntax
let result = a ?? b;
If
a
is notnull
orundefined
, it returnsa
Otherwise, it returns
b
✅ Basic Examples:
let user;
console.log(user ?? "Anonymous"); // "Anonymous"
user = "John";
console.log(user ?? "Anonymous"); // "John"
✅ Real-World Example:
function getUserName(data) {
return data.firstName ?? data.nickName ?? "Anonymous";
}
getUserName({}); // "Anonymous"
getUserName({ nickName: "CodeStar" }); // "CodeStar"
🧠 Visual: Execution Timeline
Operands: null ?? "default"
Check: nullish → use next
Result: "default"
🔹 2. Fill Any Gaps
🧩 Rewritten with Ternary:
let result = (a !== null && a !== undefined) ? a : b;
❗ Common Confusion vs ||
:
let height = 0;
console.log(height || 100); // 100 ❌ (not what we want)
console.log(height ?? 100); // 0 ✅ (correct)
⚠️ Operator Precedence Caveat
??
has low precedence:
let area = (height ?? 100) * (width ?? 50); // ✅ Safe
🚫 Syntax Restriction:
Cannot combine ??
directly with &&
or ||
:
let x = 1 && 2 ?? 3; // ❌ Syntax Error
let x = (1 && 2) ?? 3; // ✅ Correct
🔹 3. Challenge Me Deeply
🟢 Basic
Return a user-defined message if it exists; otherwise, fallback to
"No message"
.Assign default product price only if it's null/undefined.
Print the first defined value from 3 user data fields.
🟡 Intermediate
Replace
||
with??
in a form that fails when values like0
or""
are valid.Chain multiple
??
to fallback through a configuration hierarchy.Refactor a function that incorrectly uses
||
to avoid false negatives.
🔴 Advanced
Build a function
getEnvConfig
that returns config from env -> local -> default using??
.Detect and fix a logic error caused by
||
where a valid 0 score gets overridden.Create a validator where
null
andundefined
get replaced butfalse
and0
are respected.Create a utility that auto-fixes object defaults using
??
(like lodash’sdefaults
).
🎯 Bonus (Brain-Twister)
🧠 Convert a legacy ternary chain to a clean, modern equivalent using ??
, but one conditionally returns falsy values like ""
, 0
, and false
which must not be overridden.
🔹 4. Interview-Ready Questions
📘 Conceptual
What’s the difference between
||
and??
?When would you prefer
??
over||
?
🧩 Scenario-Based
A user score is
0
, and your code incorrectly replaces it with10
. Why?You're debugging a function with
return config.value || "default"
but it fails when value is0
. What would you change?
🐛 Debugging
let level = 0;
let maxLevel = level || 5; // Why is maxLevel 5 instead of 0?
✅ Best Practices
Do:
Use
??
when onlynull
orundefined
should be considered “empty.”Wrap
??
operands in parentheses when mixing with math or logical ops.
Avoid:
Using
??
with&&
or||
without parentheses.Assuming it works like
||
for all falsy values.
🔹 5. Real-World Usage
🧩 Common Use Cases
- Defaulting props in React:
const Button = ({ label }) => <button>{label ?? "Click Me"}</button>;
- Fallback config in Node.js:
const port = process.env.PORT ?? 3000;
- API fallback values:
const title = apiData.title ?? "Untitled";
📦 Libraries That Use It
React
Vue 3+
Svelte
Lodash (for defaults logic)
🔹 6. Remember Like a Pro
🧠 Mnemonic:
❓❓ “Two questions — Is it null? Is it undefined? No? Then use it!”
🧾 Cheatsheet:
Expression | Result |
null ?? "a" | "a" |
undefined ?? "b" | "b" |
0 ?? 100 | 0 |
false ?? true | false |
"" ?? "Empty" | "" |
🔹 7. Apply It in a Fun Way
🎯 Mini Project: 🛠 SmartProfile
🔧 A user profile UI that:
Shows name, nickname, or “Guest” using
??
Displays custom avatar or default image
Uses
??
in config fallbacks
🧩 Steps:
Create a
user
object with optional fields.Use
??
to fallback forname
,avatar
, andbio
.Render with default values if fields are missing.
Test with different partial/missing user data.
Bonus:
- Add a UI to toggle fields as
null
/undefined
and watch it fallback in real-time.
➕ Bonus Nuggets
🚫 Mistakes Devs Make
Using
||
for defaults without realizing0
,false
,""
will be ignored.Forgetting to wrap
??
expressions in parentheses with math/logical ops.
⚙️ Performance Tip
??
is slightly faster than chained ternaries or||
with falsy checks when onlynull
/undefined
are of concern.
🔧 Polyfill
if (a !== null && a !== undefined) return a; else return b;
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
