Skip to content

/errors/javascript/cannot-read-properties-of-undefined

TypeError: Cannot read properties of undefined (reading 'x')

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · v24.20.0updated
tool
JavaScript
exit code
1
versions
V8 9.3+ wording (Chrome 93, Node.js 16.9)
os
any

TypeError: Cannot read properties of undefined (reading 'profile') means the code evaluated something.profile while something was undefined. The name in parentheses is the property being read; the missing object is the expression to its left. With null instead of undefined the message says of null.

Reproduce it

bash
cat > app.js <<'EOF'
const users = [{ profile: { name: "Ada" } }];
try {
  console.log(users[1].profile.name);
} catch (e) {
  console.log(`${e.name}: ${e.message}`);
}
try {
  const el = null;
  console.log(el.textContent);
} catch (e) {
  console.log(`${e.name}: ${e.message}`);
}
EOF
node app.js

Output

TypeError: Cannot read properties of undefined (reading 'profile')
TypeError: Cannot read properties of null (reading 'textContent')

users[1] does not exist, so users[1].profile reads a property of undefined. The message names profile, the property that could not be read, not the missing element. Uncaught, the same error stops a Node.js script with exit code 1.

Guard optional values

bash
cat > fix.js <<'EOF'
const users = [{ profile: { name: "Ada" } }];
console.log(users[1]?.profile?.name);                // undefined, no exception
console.log(users[1]?.profile?.name ?? "anonymous"); // default value
function greet({ name } = {}) { return `hi ${name ?? "there"}`; }
console.log(greet());
EOF
node fix.js

Output

undefined
anonymous
hi there

Other engines and older wording

Before V8 9.3 the same error read TypeError: Cannot read property 'profile' of undefined. Firefox reports it as TypeError: users[1] is undefined, and Safari as undefined is not an object (evaluating 'users[1].profile').

Sources