TypeError: Cannot read properties of undefined (reading 'length')
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.
What it means
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().
Common causes
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.
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.