Common Use Cases for ??
What you'll learn: How to apply the nullish coalescing operator in real-world scenarios like default values, configuration objects, and optional parameters.
Why ?? Shines in Practice
Now that you understand the difference between nullish and falsy values, let's see where the ?? operator really earns its keep. It excels in situations where you need to distinguish between "no value provided" (null/undefined) and "a legitimate falsy value provided" (like 0, '', or false).
Default Values That Respect Falsy Inputs
function setVolume(level) {
const volume = level ?? 50; // 0 is valid, null/undefined → 50
console.log(`Volume: ${volume}`);
}
setVolume(0); // Volume: 0 (not 50!)
setVolume(undefined); // Volume: 50
This is perfect for numeric settings where zero is meaningful.
Configuration Objects
function createConfig(options) {
return {
timeout: options?.timeout ?? 3000,
retries: options?.retries ?? 3,
debug: options?.debug ?? false,
port: options?.port ?? 8080
};
}
createConfig({ port: 0, debug: false });
// { timeout: 3000, retries: 3, debug: false, port: 0 }
Notice how port: 0 and debug: false are preserved—they're not nullish!
Optional Function Parameters
function paginate(page, pageSize) {
const currentPage = page ?? 1;
const itemsPerPage = pageSize ?? 20;
const start = (currentPage - 1) * itemsPerPage;
return { start, limit: itemsPerPage };
}
paginate(0, 10); // page 0 is valid!
paginate(null, null); // Uses defaults: page 1, size 20
Key Takeaway: Use ?? when you need default values but must preserve falsy inputs like 0, '', or false. It's ideal for configurations, optional parameters, and any scenario where "nothing provided" differs from "false/zero provided."