Brainlag
  1. Library
  2. Debugging
  3. Web

Cannot read properties of undefinedWhat is "Cannot read properties of undefined"?

This TypeError means you asked for a property of something that is undefined or null. Usually an index past the end of an array or a misspelt key.

Web5 min

What JavaScript is telling you

Output
TypeError: Cannot read properties of undefined (reading 'name')

The part in brackets is the property you asked for: .name. The problem is the thing before the dot. It was undefined, and undefined has no properties at all.

So for players[3].name, the real question is: why is players[3] undefined? The common answers:

  • Past the end of an array. An array of 3 has indexes 0, 1 and 2. players[3] is undefined. Loops with <= instead of < do this.
  • A misspelt key. user.profil.avatar: user.profil does not exist, so it is undefined.
  • Data not there yet, such as a fetch you forgot to await.

How to find it

The message names the property after the dot. Find that line, then log the thing just before the dot: console.log(i, players[i]). When it prints undefined, ask how that index or key got there. Check loop limits first, then spelling.

Run it: one player too many

Press Run and read the error from the bottom up.

main.js to run
const squad = [
  { name: "Ana", level: 12 },
  { name: "Ben", level: 9 },
  { name: "Cleo", level: 15 },
];

for (let i = 0; i <= squad.length; i++) {
  console.log(squad[i].name, "is level", squad[i].level);
}

A lobby list that crashes at the end

This should list every player in the lobby with their ping, then print 3 players. It lists them and then crashes. Fix it.

exercise_1.js to run
const lobby = [
  { tag: "zara_x", ping: 32 },
  { tag: "kofi99", ping: 58 },
  { tag: "meimei", ping: 41 },
];
for (let i = 1; i <= lobby.length; i++) {
  console.log(lobby[i].tag + " " + lobby[i].ping + "ms");
}
console.log(lobby.length + " players");

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.