/errors/javascript/cannot-read-properties-of-undefined
TypeError: Cannot read properties of undefined (reading 'x')
- 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
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.jsOutput
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
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.jsOutput
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
- developer.mozilla.orgdeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_property
- developer.mozilla.orgdeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
- developer.mozilla.orgdeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing