πŸŽ‰ We just launched our new React course! Get it with 20% off! πŸŽ‰

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

Ferenc Almasi β€’ πŸ”„ 2023 March 17 β€’ πŸ“– 2 min read
  • twitter
  • facebook

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
undefined.map()
Copied to clipboard!

Try to run the above code in your console, and you will end up with the very same error. This is a common pitfall that can be easily avoided using the following solution.

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

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 (
    <React.Fragment>
        {posts.map(post => <Card details={post} />)}
    </React.Fragment>
)
Copied to clipboard!
  • 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

Recommended

Ezoicreport this ad
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_~