TypeError: Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length') in JavaScript means you asked for .length of a value that is undefined (or null). An array index past the end, a missing argument, or a match() that found nothing.
How do I fix TypeError: Cannot read properties of undefined (reading 'length')?
TypeError: Cannot read properties of undefined (reading 'length') means you read .length on a value that is undefined. Common causes are a loop with i <= arr.length, a function called without its argument, or String.match() returning null. Use i < arr.length, give the parameter a default like list = [], and write (text.match(re) ?? []).length.
- 1. Check the loop boundIn a loop, i <= arr.length reads arr[arr.length], which is undefined. Use i < arr.length.
- 2. Check match() resultsIf the message says null, look for String.match(). It returns null when nothing matches.
- 3. Check function argumentsLog the parameter inside the function. A caller that skips the argument passes undefined.
What does TypeError: Cannot read properties of undefined (reading 'length') mean?
Strings and arrays have .length; undefined and null have nothing. Because JavaScript returns undefined for missing indexes and properties instead of throwing, the real mistake usually happened a line or two earlier. The null form — "of null (reading 'length')" — points almost always at String.match().
Why does TypeError: Cannot read properties of undefined (reading 'length') happen?
1. Loop bound one past the end
arr[arr.length] is undefined, and reading .length on it throws.
Breaks
for (let i = 0; i <= words.length; i++) {
total += words[i].length;
}Works
for (let i = 0; i < words.length; i++) {
total += words[i].length;
}2. String.match() with no match
match returns null — not an empty array — when nothing matches.
Breaks
const count = text.match(/\d/g).length;Works
const count = (text.match(/\d/g) ?? []).length;3. A function called without its argument
A missing argument is undefined inside the function.
Breaks
function isEmpty(list) {
return list.length === 0;
}
isEmpty();Works
function isEmpty(list = []) {
return list.length === 0;
}How to find it in your own code
Log the object right before .length. If the line is inside a loop, log the index too — an index equal to the length is an off-by-one. If it comes from match(), find() or a lookup, handle the "nothing found" result explicitly with ?? [] or a guard.
Practise null and undefined errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.