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

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


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!
Remove ads
Remove ads

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
🎉 Thank you for subscribing to our newsletter. x