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

Failed Destructuring and Errors

Understand when destructuring throws errors versus when it assigns undefined.

Failed Destructuring and Errors

You'll learn: When destructuring throws runtime errors versus when it silently assigns undefined.

When Destructuring Fails Safely

Most of the time, destructuring in JavaScript is forgiving. If you try to destructure more variables than there are values, the extra variables simply receive undefined:

const [a, b, c] = [1, 2];
console.log(c); // undefined

Similarly with objects, accessing non-existent properties gives you undefined:

const { name, age } = { name: "Alice" };
console.log(age); // undefined

When Destructuring Throws Errors

Destructuring will throw a TypeError if you try to destructure from values that aren't destructurable:

Arrays: You can only destructure iterables. Trying to destructure null or undefined fails:

const [x] = null; // TypeError: null is not iterable
const [y] = undefined; // TypeError: undefined is not iterable

Objects: You can destructure from any non-null, non-undefined value (primitives get boxed), but null and undefined throw errors:

const { prop } = null; // TypeError: Cannot destructure property 'prop' of 'null'
const { prop } = undefined; // TypeError: Cannot destructure property 'prop' of 'undefined'

Think of It Like This

Destructuring is like opening a box. If there's nothing inside the box (empty array, missing properties), that's fine—you just get nothing. But if there's no box at all (null or undefined), JavaScript can't even begin the unpacking process and throws an error.

Key Takeaway: Destructuring assigns undefined for missing values but throws a TypeError when attempting to destructure null or undefined themselves. Always ensure your source exists before destructuring.