Uncaught TypeError: Cannot read properties of undefined [SOLVED]
The error “Uncaught TypeError: Cannot read properties of undefined” can occur for several reasons, two of the most common ones are:
- When you try to access a property on the primitive value
undefined
- In an array, when you try to access an index that doesn’t exist
In this article I explain several ways to fix this error.
Table of Contents
When you try to access a property on the undefined value
The most common reason for this error is trying to access a property on a variable that points to undefined
.
For example, the following code will throw “Uncaught TypeError: Cannot read properties of undefined“.
// If you declare a variable but you don't assign a value to it
// the variable will point to undefined
let user;
// Cannot read properties of undefined (reading 'name')
user.name;
The error is very clear and descriptive: Cannot read properties of undefined (reading ‘name’). The variable points to undefined
but does not have a property of name
.
Solution 1: The optional chaining (?.) operator
The optional chaining operator (?.
) is a fail-safe way to access nested properties of objects, even if no intermediate property exists.
In other words, this operator checks that the property does not contain the value null
or undefined
before attempting to access it. If the value is undefined
or null
, the operator “short-circuits” instead of throwing an exception.
let user; // undefined
console.log(user.name); // ❌
// Using the optional chaining operator
console.log(user?.name); // 👉 undefined
console.log(user?.name?.first) // 👉 undefined
// Using if/else
if (user?.name) {
console.log(user.name);
} else {
console.log('user.name not found');
}
// Using the conditional (ternary) operator
user?.name ? console.log(user.name) : console.log('user.name not found')
The operator (?.
) works similarly to the chaining operator (.) except that instead of raising an error if a reference is null
or undefined
, the expression does a short-circuit evaluation with a return value of undefined
.
Solution 2: The logical operator AND (&&)
The logical operator AND (&&) compares expressions from left to right, returning the first falsy value it finds; if all values are true, then it returns the last value.
const user = undefined;
// Using the logical operator AND (&&)
console.log(user && user.name); // 👉 undefined
// If all values are truthy, then it returns the last one
const contact = {
address: {
city: 'Preston'
}
}
console.log(contact && contact.address && contact.address.city); // 👉 Preston
You can use the logical AND operator (&&) in a similar way to the optional chaining operator (?.)
let user; // undefined
if (user?.name?.first) {
console.log(user.name.first);
}
if (user && user.name && user.name.first) {
console.log(user.name.first);
}
Solution 3: The nullish coalescing operator (??)
The null coalescing operator (??) treats null
and undefined
in a similar way. This operator returns its right-hand side operand when its left-hand side operand is null
or undefined
. Otherwise, it returns its left-hand side operand.
const username = undefined;
// Uncaught TypeError: Cannot read properties of undefined (reading 'toLowerCase')
const error = username.toLowerCase(); // ❌
const lowercase = (username ?? 'testUser').toLowerCase(); // ✅ testUser
You can use the null union operator (??) to prevent the Cannot read properties of undefined error
, by providing a default value when the variable has a falsy value, such as null
or undefined
.
const company = undefined;
const companyName = (company ?? { name: 'Acme' }).name;
console.log(companyName) // 👉 Acme
In an array, when you try to access an index that doesn’t exist
In the following example, we have an array with one element at index 0, but we are trying to access an element at index 2, which does not exist.
const arr = [{
name: 'Leo'
}];
// Uncaught TypeError: Cannot read properties of undefined (reading 'name')
console.log(arr[2].name); // ❌
Solution 1: Use the optional chaining operator (?.) on the array
You can use the operator (?.
) to make sure that the array index exists before trying to access the property.
const arr = [{
name: 'Leo'
}];
console.log(arr[2].name); // ❌
console.log(arr[2]?.name); // undefined ✅
Use the same solution when you have to access elements nested in indices that may not exist.
const nested = [];
// Uncaught TypeError: Cannot read properties of undefined (reading '0')
console.log(nested[0][0][0]); // ❌
console.log(nested?.[0]?.[0]?.[0]); // undefined ✅
Solution 2: Use the logical operator AND (&&) on the array
Similarly, you can use the operator (&&
) to make sure that the element exists before trying to access the property.
const arr = [{
name: 'Leo'
}];
console.log(arr[2].name); // ❌
console.log(arr[2] && arr[2].name); // undefined ✅
Level Up 🌟
You can combine the optional chaining operator (?.
) and the null coalescing operator (??
) to return a value if the variable or object property returns undefined
.
In the following example, since the user
variable points to the value undefined
, and the name
property does not exist, it will return the value “Pedro”.
const user = undefined;
const name = user?.name ?? 'Pedro';
console.log(name); // 👉 Pedro
const country = user?.address.?country ?? 'USA';
console.log(country); // 👉 USA
Summary
The “Uncaught TypeError: Cannot read properties of undefined” error occurs when you try to access a property or method on a variable that contains the primitive value undefined
. To fix the error, simply check if the variable’s value is not undefined
before attempting to access the property or method.