🎄 Get 50% off from our JavaScript course for the holidays! 🎄

Fix "cannot read properties of undefined (reading map)" in JS

Ferenc Almasi • 2022 July 11 • 📖 2 min read

The "Uncaught TypeError: Cannot read properties of undefined (reading 'map')" error occurs in JavaScript, whenever you try to use the array map method on a variable that is undefined. This can usually happen in React, whenever you need to loop through an array of elements and display them.

{posts.map(post => <Card details={post} />)}
Copied to clipboard!

However, the array on which you are executing the map is undefined. This means that JavaScript sees the following code, and throws the above error:

// Trying to run map on undefined
{undefined.map(post => <Card details={post} />)}

// Or simply try to run in your console
Copied to clipboard!

Try to run the above code in your console, and you will end up with the very same error.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

How to Fix the Error?

In order to fix the error, you need to make sure that the array is not undefined. In order to do this, the simplest way is to use optional chaining.

{posts?.map(post => <Card details={post} />)}
Copied to clipboard!

You can use optional chaining by introducing a question mark after the variable. You can also use a logical AND, or use an if check prior to rendering to prevent running into issues.

// Using logical AND
{posts && posts.map(post => <Card details={post} />)}

// Using an if check
if (!posts) {
    return null

// Here post will not be undefined anymore
return (
        {posts.map(post => <Card details={post} />)}
Copied to clipboard!
Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More


🎉 Thank you for subscribing to our newsletter. x