A villain that has been appearing in the code of many beginner programmers: “Cannot read properties of undefined (reading ‘length’)”.

Do not panic; this is one of the most common problems in the JavaScript ecosystem, and practically every developer goes through it, including me!
What does this error mean?
The error occurs when the variable you are trying to access points to a memory address containing the primitive value undefined. Since undefined (like null) is not an object, it has neither a prototype nor properties. Trying to read any value from it instantly triggers a TypeError because you are demanding that the JavaScript engine execute an impossible operation on an “empty” primitive type.
To summarize, JavaScript is trying to measure the size (the .length property) of something that is still nonexistent or has not been defined in memory.
Why does it happen?
- API data not yet loaded: You try to read the size of the list before the server’s response appears.
- Uninitialized variables: You declared
let lista;but forgot to assign the brackets[]. - Accessing nonexistent properties: You tried to access
usuario.compras.length, but theusuarioobject does not have thecompraskey.
Quick Fix: Stop the crash right now
In the case you need an immediate solution to prevent your app from breaking, use Optional Chaining (?.) with a Fallback Value (??).
Instead of this:
// ❌ This will crash if 'data' is missing
console.log(data.length);
Do this:
// ✅ Safe! Returns 0 instead of throwing an error
console.log(data?.length ?? 0);
The ?. checks if the variable exists, and ?? 0 ensures that if it doesn’t, you at least get a zero.
Some ways to solve this
1. Optional Chaining Operator
It is a sophisticated solution. The ?. operator checks if the value before it is null or undefined before accessing the property. If ‘dados’ is undefined, the result will be undefined instead of an error.
const size = data?.length;
console.log(size);
// If 'data' or 'orders' are undefined, the result is undefined, NOT an error.
Why use it: This solution keeps the code clean, and I use it daily without the need for multiple if blocks. It is ideal for modern interfaces (React/Vue) where state data might take a few milliseconds to populate.
2. Short-Circuit Pattern and Fallback Values
Often, just “not breaking” is not enough; you need a functional value so the rest of the logic (like a map or for loop) continues operating. We use the logical operator || or ?? (Nullish Coalescing) to ensure the variable is always at least an empty array.
Example:
// Ensuring the variable is iterable
const products = apiResponse.data || [];
// Now .length is safe and will return 0 if there is no data
if (products.length > 0) {
renderProducts(products);
}
A very good secure code practice is to ensure that your variable always has an expected type, such as an empty array.
// If the data comes back null from the API, we assume an empty array
const products = response.data || [];
console.log(products.length); // Result: 0 (no error!)
3. Classic Conditional Verification
For beginners, the if statement helps keep the code flow readable and explicit.
if (typeof myVariable !== 'undefined' && myVariable !== null) {
console.log(myVariable.length);
} else {
console.log("The data is still loading...");
}
Errors to avoid
- Always initialize your variables: If you expect a list, start with
let itens = [];. - Use TypeScript: If possible, TypeScript will warn you about this error before you even run the code.
- Handle loading states: In frameworks like React or Vue, always check if the data exists before rendering components that depend on
.length.
Conclusion
“Cannot read properties of undefined (reading ‘length’)” is just JavaScript being strict with data safety. By using tools like Optional Chaining or default values, you make your code better and more professional.
FAQ
Why does the error say "reading 'length'" if I didn't type the word 'length' anywhere in my code?
Answer: This often happens because many built-in JavaScript functions or external libraries (like React, Lodash, or Chart.js) try to read the size of your data automatically. If you pass a variable to a function that expects an array, but that variable is undefined, the library's internal code will attempt to access .length and trigger the error in your console. Always double-check the data you are passing into third-party functions or components.