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

Ferenc Almasi β€’ Last updated 2023 March 17 β€’ Read time 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.

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

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:

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

// Or simply try to run in your console
undefined.map()

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.


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.

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

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.

Copied to clipboard! Playground
// 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>
)
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.