Skip to main content

How to Resolve "TypeError: Cannot destructure property of undefined or null" Error in JavaScript

The TypeError: Cannot destructure property 'X' of 'Y' as it is undefined. (or null) is a very common error in JavaScript. It occurs when you try to use destructuring assignment on a value that is undefined or null, which are not objects and therefore have no properties to destructure.

This guide will explain the root cause of this error and teach you the modern, standard solutions for preventing it. You will learn how to provide default values and fallback objects, ensuring your destructuring assignments are safe and robust, even when the data you are working with is missing.

Understanding the Root Cause: Destructuring a Non-Object

Destructuring is a syntax for unpacking values from arrays or properties from objects into distinct variables. It only works when the value on the right-hand side of the assignment is an object (or an array). If that value is undefined or null, JavaScript cannot "unpack" any properties from it, and it throws a TypeError.

The Error in Action (with undefined)

let user; // user is declared but not initialized, so its value is undefined

// ⛔️ TypeError: Cannot destructure property 'name' of 'user' as it is undefined.
const { name } = user;

The Error in Action (with null)

This often happens with functions that might return null, like document.querySelector.

const element = document.querySelector('.non-existent'); // element is null

// ⛔️ TypeError: Cannot destructure property 'id' of 'element' as it is null.
const { id } = element;

The simplest and most common solution is to use the logical OR (||) or nullish coalescing (??) operator to provide an empty object ({}) as a fallback if the value you are destructuring is falsy or nullish.

When you do const { prop } = myVar || {}, if myVar is undefined, null, false, 0, or '', the expression myVar || {} evaluates to the empty object {}. Destructuring then proceeds on this empty object, which is a safe operation.

Solution with ||

const user = undefined;

// If user is falsy (like undefined), use the empty object instead.
const { name } = user || {};

// No error is thrown. `name` is simply undefined because it doesn't exist on {}.
console.log(name); // Output: undefined

Solution with ??

The nullish coalescing operator (??) is even better, as it only triggers the fallback for undefined or null, not for other falsy values like '' or 0.

const response = null;

// If response is null or undefined, use the empty object.
const { data } = response ?? {};

console.log(data); // Output: undefined

Solution 2: Providing Default Values for Function Parameters

This error frequently occurs in functions when an object argument is not provided. The best way to handle this is to set a default parameter for the argument.

Example of code with problems:

function printUserName(user) {
// ⛔️ TypeError if the `user` argument is not provided.
const { name } = user;
console.log(name);
}

printUserName(); // Called with no arguments, so `user` is undefined.

The solution is to set the default value of the user parameter to an empty object.

function printUserName(user = {}) {
// If `user` is not provided, it defaults to `{}`.
const { name } = user;
console.log(name); // Output: undefined (no error)
}

printUserName();

An Alternative: Using Optional Chaining (?.)

If you don't need to destructure but just want to safely access a property, the optional chaining operator (?.) is a great alternative. It short-circuits and returns undefined if any part of the chain is null or undefined.

const user = undefined;

// This does not use destructuring, but it safely gets the name property.
const name = user?.name;

console.log(name); // Output: undefined
note

This is a good choice if you only need one or two properties.

Practical Example: Safely Destructuring an API Response

This is a common real-world scenario. A function fetches data from an API, but the response might not always contain the expected data object.

Example of code with problems:

function processApiResponse(response) {
// ⛔️ TypeError if response is { success: false } (no `data` property)
// or if response is null or undefined.
const { user, products } = response.data;
console.log(user, products);
}

The Robust Solution:

function processApiResponse(response) {
// Provide a fallback for response itself, and another for response.data
const { user, products } = response?.data ?? {};

console.log('User:', user); // Output: User: undefined
console.log('Products:', products); // Output: Products: undefined
}

// Call with a missing `data` property
processApiResponse({ success: true });

This code is robust. It handles a null response, a response without a data property, and a successful response all without throwing an error.

Conclusion

The "Cannot destructure property of undefined or null" error is a signal to make your code more defensive.

To fix it:

  • The best and most common solution is to provide a fallback empty object ({}) when destructuring, using the nullish coalescing (??) or logical OR (||) operators: const { prop } = myVar ?? {};.
  • When working with function arguments, set a default parameter to an empty object: function myFunc(options = {}) { ... }.
  • Consider using optional chaining (?.) as a simpler alternative if you only need to access a few properties without destructuring.