Course contentsShow
← JavaScript
Lesson 937 of 2,72321. DestructuringFree lesson

Destructuring null and undefined

Handle cases where the source value is null or undefined using optional patterns.

Destructuring null and undefined

You'll learn how to safely handle destructuring when the source value might be null or undefined.

The Problem with Absent Values

When you try to destructure from null or undefined, JavaScript throws a TypeError because there's nothing to unpack. It's like trying to unpack a suitcase that doesn't exist—JavaScript doesn't know what to do.

// These will throw errors:
const { name } = null;          // TypeError!
const [first] = undefined;      // TypeError!

This happens because destructuring tries to access properties or iterate over the value, but null and undefined have no properties.

Protecting Against Errors

You can guard against this by providing a fallback value using the OR operator (||) or nullish coalescing (??):

// Safely destructure with a fallback object
const data = null;
const { name = 'Anonymous' } = data || {};
// name is 'Anonymous' - no error!

// Array destructuring with fallback
const list = undefined;
const [first = 'default'] = list || [];
// first is 'default' - no error!

The pattern data || {} ensures you're destructuring from an empty object (or array) if data is null or undefined. Then your default values kick in.

When This Matters

This technique is crucial when working with API responses, optional function parameters, or any situation where data might be missing:

function greet(user) {
  const { name = 'Guest' } = user || {};
  return `Hello, ${name}!`;
}

greet({ name: 'Alice' }); // "Hello, Alice!"
greet(null);               // "Hello, Guest!"

Key Takeaway: Always use || {} (for objects) or || [] (for arrays) when destructuring from values that might be null or undefined to avoid runtime errors.