How to Resolve "TypeError: Cannot read properties of undefined (reading 'length')" Error in JavaScript
The TypeError: Cannot read properties of undefined (reading 'length') is a very common error in JavaScript. It occurs when you try to access the .length property of a variable that holds the value undefined, instead of an array or a string.
This guide will explain what the .length property is, the common reasons your variable might be undefined, and the standard, robust solutions to fix this error, including providing default values and using modern optional chaining.
Understanding the .length Property
In JavaScript, the .length property is a feature of arrays and strings.
- For an array, it returns the number of elements:
['a', 'b'].lengthis2. - For a string, it returns the number of characters:
'hello'.lengthis5.
Other data types, like numbers, booleans, null, and undefined, do not have a .length property.
Understanding the Error: Why undefined?
The error message Cannot read properties of undefined (reading 'length') tells you exactly what happened:
- It tried to read the property
length. - It tried to read it from a variable whose value was
undefined.
Example with error:
let myVariable; // This variable has no assigned value, so it is `undefined`
// The .length property does not exist on `undefined`.
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'length')
console.log(myVariable.length);
Common Causes of the Error
This error typically happens for two main reasons:
1. A variable was declared but never initialized
let userList; // `userList` is undefined
// ⛔️ Throws the error
if (userList.length > 0) {
// ...
}
Solution: Always initialize variables to a sensible default, like [] for an array or "" for a string.
2. An operation resulted in undefined
This often happens when you try to access an array element or object property that doesn't exist.
const nestedArray = [
['apple', 'banana'], // index 0
];
const subArray = nestedArray[1]; // Accessing an index that is out of bounds
console.log(subArray);
// Output: undefined
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'length')
console.log(subArray.length);
Solution 1: Provide a Fallback to a Default Value
If a variable might be undefined (e.g., from an API call or a function that can fail), the easiest way to prevent the error is to provide a default value using the logical OR (||) operator.
const dataFromApi = undefined;
// If `dataFromApi` is falsy (like undefined), use an empty array instead.
const items = dataFromApi || [];
// ✅ This is now safe. The .length of an empty array is 0.
console.log(items.length);
// Output: 0
This is a very common and effective pattern for ensuring a variable is always safe to access.
Solution 2: Use a Conditional Check Before Accessing
A more explicit and often more readable solution is to check that the variable is a valid type before you try to access its .length property.
Solution for Arrays
Use the Array.isArray() method.
const items = undefined;
if (Array.isArray(items)) {
console.log(`The array has ${items.length} items.`);
} else {
console.log('The variable is not an array.');
}
Solution for Strings
Use the typeof operator.
const message = undefined;
if (typeof message === 'string') {
console.log(`The message is ${message.length} characters long.`);
} else {
console.log('The variable is not a string.');
}
Solution 3: Use Optional Chaining (?.) for Safe Access
For modern JavaScript (ES2020 and newer), the optional chaining operator (?.) is the most concise and elegant solution. It allows you to safely try to access a property. If the value on the left is null or undefined, the expression "short-circuits" and returns undefined instead of throwing an error.
const items = undefined;
// The `?.` checks if `items` is null or undefined. Since it is,
// the .length access is never made. The expression returns `undefined`.
const length = items?.length;
console.log(length); // Output: undefined
You can combine this with the nullish coalescing operator (??) or logical OR (||) to provide a default value.
const items = undefined;
// If the optional chain results in `undefined`, the `||` provides a fallback of 0.
const length = items?.length || 0;
console.log(length); // Output: 0
This is the recommended modern syntax for safely accessing properties that might not exist.
Conclusion
The TypeError: Cannot read properties of undefined (reading 'length') error is a clear signal that you are trying to measure a variable that is not a string or an array.
To fix it, you must add a safeguard before accessing the .length property:
- Initialize your variables: Always assign a default value (like
[]or"") upon declaration. - Provide a Fallback: Use the logical OR operator for a quick and safe default:
const items = data || [];. - Use a Conditional Check: Use
if (Array.isArray(items))for clear and robust code. - Use Optional Chaining (Best for Conciseness): Use
const length = items?.length || 0;for a clean, modern, and safe way to access the property.