Solve - map is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Thom Holmes

Solve - map is not a function Error #

The "TypeError: map is not a function" occurs when we call the map() method on an object that is not an array. To solve the error, console.log the value you're calling the map() method on and make sure to only call the map method on valid arrays.

typeerror map is not a function

Here is an example of how the error occurs.

index.js
const obj = {}; // ⛔️ Uncaught TypeError: map is not a function const result = obj.map(element => { return element + 1; });

We called the Array.map() method on an object and got the error back.

To solve the error, console.log the value you're calling the map method on and make sure it's a valid array.

index.js
const arr = [1, 2, 3]; const result = arr.map(element => { return element + 1; }); console.log(result); // 👉️ [2, 3, 4]

You can conditionally check if the value is an array by using the Array.isArray method.

index.js
const arr = 'test'; const result = Array.isArray(arr) ? arr.map(element => element + 1) : []; console.log(result); // 👉️ []

We used a ternary operator, which is very similar to an if/else statement.

If the value is an array, we return the result of calling the map method on it, otherwise we return an empty array. This way, you won't get an error, even if the value is not an array.

If the value is fetched from a remote server, make sure it is of the type you expect it to be by logging it to the console and make sure you have parsed it to a native JavaScript array before calling the map method on it.

If you have an array-like object which you're trying to convert to an array before calling the map method, use the Array.from method.

index.js
const set = new Set([1, 2, 3]); const result = Array.from(set).map(element => element + 1); console.log(result); // 👉️ [2, 3, 4]

Before calling the map method, we convert the value to an array. This would also work for array-like objects like the NodeList returned from calling the getElementsByClassName method.

If you're using React.js, you can check if the value is an array before mapping over it in the following way.
App.js
{Array.isArray(value) ? (value).map(e => /* your code */) : null}

We used a ternary operator to check if the value is an array.

If it is an array, we return the result of calling the map() method on it, otherwise we return a null value.

Further Reading #

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