Skip to content
FR
  1. LuzineDebug
  2. JavaScript & Node.js
  3. TypeError: Cannot read properties of undefined (…
JavaScript & Node.js Beginner ≈ 10 min to fix

Fix "Cannot read properties of undefined" in JavaScript

Error message
TypeError: Cannot read properties of undefined (reading 'map')
  • TypeError: Cannot read property 'map' of undefined
  • TypeError: Cannot read properties of null (reading 'addEventListener')
  • TypeError: undefined is not an object (evaluating 'data.items')
  • TypeError: can't access property "map", data.items is undefined
  • TypeError: data is undefined
In short

You are reading a property (here map) on a value that is undefined or null. The object before the dot does not exist yet or does not have the expected shape: check where it comes from, then guard the access with ?. and a default value ?? [].

Be the first to confirm this fix

What this error means

In JavaScript, only objects (and boxed primitives) have properties. When the engine evaluates data.items.map, it first reads data.items; if that value is undefined or null, it cannot look up map on it and throws a TypeError. The name in parentheses is the property you tried to read, not the missing one: the culprit is always the expression just to its left. Chrome, Edge and Node.js (V8) print "Cannot read properties of undefined (reading 'x')", Firefox prints "x is undefined" and Safari "undefined is not an object". The stack trace gives the exact file and line.

Common causes

  1. Async data not loaded yet: on the first render (React, Vue) or before a fetch resolves, the variable is still undefined.
  2. API response shaped differently than expected: the array lives in data.results instead of data.items, or the API returns an error { "message": ... } instead of the data.
  3. DOM element not found: document.querySelector() returns null because the selector is wrong or the script runs before the HTML is parsed.
  4. Missing index or key: users[5].name when the array only has 3 items, or a misspelled key.
  5. Lost this: a method passed as a callback without bind or an arrow function, so this is undefined in strict mode.

Step-by-step fix

  1. Find the failing expression

    Open the line shown in the stack trace. In a.b.c.map, the undefined value is the one right before map. Add a console.log just before it to see its real value.

    javascript
    console.log('data =', data);
    console.log('items =', data?.items);
  2. Check the real data shape

    In the DevTools Network tab, open the API response and compare its keys with the ones in your code. Paste the JSON into a formatter to read its structure easily.

  3. Guard the access with ?. and ??

    Optional chaining ?. returns undefined instead of throwing, and ?? provides a default value. This is the most common fix for data that may be missing.

    javascript
    const items = data?.items ?? [];
    const names = items.map((item) => item.name);
  4. Initialize state and handle loading (React)

    Give state a consistent initial value ([] for a list) and render a loading state until the data has arrived.

    javascript
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    
    useEffect(() => {
      fetch('/api/users')
        .then((res) => res.json())
        .then((data) => setUsers(data.users ?? []))
        .finally(() => setLoading(false));
    }, []);
    
    if (loading) return <p>Loading...</p>;
    return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
  5. Wait for the DOM before using it

    If the error comes from querySelector, load the script with defer or wait for DOMContentLoaded, and check the element exists before using it.

    javascript
    document.addEventListener('DOMContentLoaded', () => {
      const button = document.querySelector('#save');
      if (!button) return;
      button.addEventListener('click', save);
    });

Did this fix work for you?

Confirm it in one click: it will rise for the next developers stuck on the same error.

Keep it from coming back

  • Enable TypeScript with "strict": true: the compiler flags access to possibly undefined values before runtime.
  • Validate API responses at the boundary (for example with Zod) instead of assuming their shape everywhere in the code.
  • Always initialize state and variables with a value of the right type ([], {}, '') instead of leaving them undefined.

Frequently asked questions

What is the difference between "Cannot read property of undefined" and "Cannot read properties of undefined"?

It is the same error. V8 (Chrome 91+, Node.js 16.9+) simply changed the wording to "Cannot read properties of undefined (reading 'x')".

Why does my React component crash on first render even though the data arrives?

The first render happens before the fetch resolves, so state still holds its initial value. Initialize it with [] or render a loading state.

Should I put ?. everywhere to avoid this error?

No. Use it where a value can legitimately be missing. Elsewhere, a visible error helps you spot a real bug instead of hiding it.

Useful tools for this error

More JavaScript & Node.js errors

All JavaScript & Node.js errors →