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

manoj ymkmanoj ymk
4 min read

✅ 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 not null or undefined, it returns a

  • 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

  1. Return a user-defined message if it exists; otherwise, fallback to "No message".

  2. Assign default product price only if it's null/undefined.

  3. Print the first defined value from 3 user data fields.

🟡 Intermediate

  1. Replace || with ?? in a form that fails when values like 0 or "" are valid.

  2. Chain multiple ?? to fallback through a configuration hierarchy.

  3. Refactor a function that incorrectly uses || to avoid false negatives.

🔴 Advanced

  1. Build a function getEnvConfig that returns config from env -> local -> default using ??.

  2. Detect and fix a logic error caused by || where a valid 0 score gets overridden.

  3. Create a validator where null and undefined get replaced but false and 0 are respected.

  4. Create a utility that auto-fixes object defaults using ?? (like lodash’s defaults).

🎯 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 with 10. Why?

  • You're debugging a function with return config.value || "default" but it fails when value is 0. What would you change?

🐛 Debugging

let level = 0;
let maxLevel = level || 5; // Why is maxLevel 5 instead of 0?

✅ Best Practices

Do:

  • Use ?? when only null or undefined 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:

ExpressionResult
null ?? "a""a"
undefined ?? "b""b"
0 ?? 1000
false ?? truefalse
"" ?? "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:

  1. Create a user object with optional fields.

  2. Use ?? to fallback for name, avatar, and bio.

  3. Render with default values if fields are missing.

  4. 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 realizing 0, 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 only null/undefined are of concern.

🔧 Polyfill

if (a !== null && a !== undefined) return a; else return b;
0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk