Nullish Coalescing: The ?? Operator

Practical Example

// Traditional way
let userConfig = {
  theme: null,
  notifications: undefined
};

// Old approach
userConfig.theme = userConfig.theme || 'dark';
userConfig.notifications = userConfig.notifications || true;

// With nullish coalescing
userConfig.theme ??= 'dark';
userConfig.notifications ??= true;

console.log(userConfig);
// { theme: 'dark', notifications: true }

Why It Matters

The nullish coalescing operator (??) is a game-changer for handling null/undefined values. Unlike ||, it only falls back to the right-hand value when the left is null or undefined, not for other falsy values like 0 or ''.

Common Use Cases:

  • Default values in function parameters
  • API response handling
  • Configuration management
  • State initialization in frameworks