Solve - Undefined is not Iterable Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

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

index.js
// โ›”๏ธ undefined is not iterable const [a, b] = undefined;

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

index.js
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.

index.js
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.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee