Solve - Undefined is not Iterable Error in JavaScript


Borislav Hadzhiev

Last updated: Oct 19, 2021


Check out my new book

Solve - Undefined is not Iterable Error in JavaScript #

The error undefined is not iterable occurs when we try to use array destructuring with an undefined value to the right hand-side, e.g. const [name] = undefined. To solve the error make sure to only use array destructuring on valid arrays.

typeerror undefined is not iterable

// ⛔️ undefined is not iterable const [a, b] = undefined;

To solve the error you can provide a fallback value of an empty array.

const [a, b] = undefined || [];

We used the logical OR (||) operator, which returns the value to the right if the value to the left is falsy (e.g. undefined).

The falsy values in JavaScript are: null, undefined, 0, false, "" (empty string), NaN (not a number).

If any of the six aforementioned values is to the left of the logical OR (||) operator, we return an empty object, which would allow us to avoid the "cannot destructure property of null" error.

If you can't track down where exactly the error occurs, look at your error message in the browser's console or your terminal (if using Node.js).

typeerror undefined is not iterable

The screenshot above shows that the error was thrown in the index.js file on line 4.

The error might also occur if you're calling a function that expects an array, but don't provide the parameter.

function hello(arr) { const [a, b] = arr; } // ⛔️ undefined is not iterable hello();

Trying to destructure from an undefined value throws the error. In this scenario, you can either pass a fallback value using the logical OR (||) operator or set a default value for the function parameter.

This code snippet shows how to do both.

function hello(arr = []) { const [a, b] = arr || []; } hello();

If no value is provided when calling the function or an undefined value is passed, the value for the arr variable is set to an empty array.

Use the search field on my Home Page to filter through my more than 3,000 articles.