Skip to content

TypeError: Cannot read properties of undefined (reading 'length')

Error message

                Cannot read properties of undefined (reading 'length')
              

Quick summary

You accessed .length on something that is undefined — usually a variable that was never assigned or a lookup that returned undefined.

Why this happens

  • An array or string variable is undefined when .length is accessed

  • A function returned undefined and the caller accessed .length on the result

  • An API response field is missing, leading to undefined before .length

Minimal example

✗ Broken code
let items;
console.log(items.length);
✓ Fixed code
let items;
console.log(items?.length);

items is undefined, so accessing .length throws. Optional chaining (?.) returns undefined instead.

How to diagnose

  • Log the variable before accessing .length to confirm it is undefined

  • Trace where the variable should have been assigned or returned

  • Check if an API response or user input is missing the expected field

How to fix

  • Add a guard check: if (arr) { console.log(arr.length); }

  • Use optional chaining: arr?.length (returns undefined instead of throwing)

  • Provide a default value: const arr = data || [];

How to prevent

  • Use optional chaining (?.) for uncertain property accesses

  • Validate inputs and API responses before using them

Related Resources

Related Glossary

Related Lessons

  • Arrays

    Learn about array properties.

← Back to language