Nullish Coalescing for Better Defaults

1 min read

The nullish coalescing operator (??) provides a fallback value only when the left side is null or undefined, unlike the logical OR (||) which treats all falsy values (0, '', false) as requiring the default.

// ❌ Wrong - empty string is falsy
const title = post.title || "Untitled";

// ✅ Better - only null/undefined trigger default
const title = post.title ?? "Untitled";

// Examples
const score = 0;
console.log(score || 100); // 100 (wrong!)
console.log(score ?? 100); // 0 (correct!)

const empty = "";
console.log(empty ?? "default"); // '' (preserves empty string)

More on JavaScript

Validate on Backend. Always.

Frontend validation improves user experience. It shows instant errors and prevents obvious mistakes like empty fields or invalid email formats. But frontend validation is never security. Anyone can bypass it using DevTools, Postman, or by directly calling your API. That’s why backend validation is mandatory it protects your database and business logic from invalid or malicious data.

Recent Tips

Validate on Backend. Always.

Frontend validation improves user experience. It shows instant errors and prevents obvious mistakes like empty fields or invalid email formats. But frontend validation is never security. Anyone can bypass it using DevTools, Postman, or by directly calling your API. That’s why backend validation is mandatory it protects your database and business logic from invalid or malicious data.

Nullish Coalescing (??) for Better Defaults in JavaScript | thehardik