Imagine you're at a buffet, eagerly approaching what you think is the dessert table, only to find an empty space where the chocolate cake should be. That disappointing moment? That's pretty much what happens in your code when you encounter the infamous "Cannot read properties of undefined" error.
Just as you can't slice a piece of cake that isn't there, JavaScript can't read a property of an object that doesn't exist. But don't worry! Unlike that missing cake (which is truly a tragedy), this JavaScript error is something we can fix.
In this guide we’ll unpack this common coding hiccup, understand why it happens, and explore several ways to prevent and handle it.
What Causes “TypeError: Cannot Read Property of Undefined”?
This error happens when you attempt to use a variable or object that hasn't been properly initialized or doesn't exist.
Undefined means that a variable has been declared but has not been assigned a value, or you're trying to access a property that doesn't exist on an object.
In JavaScript, properties and functions can only belong to objects. Since undefined
is not an object type, calling a function or accessing a property on such a variable causes the TypeError: Cannot read property of undefined
.
To fix this, you can:
- Ensure the object exists before accessing its properties
- Use optional chaining (obj?.x) to safely access nested properties
- Provide default values using the OR operator (||) or nullish coalescing operator (??)
Let’s go through an example.
“TypeError: Cannot Read Property of Undefined” Example
Here’s an example of a JavaScript TypeError: Cannot read property of undefined
thrown when a property is attempted to be read on an undefined variable:
function myFunc(a) {
console.log(a.b);
}
var myVar;
myFunc(myVar);
Since the variable myVar
is declared but not initialized, it is undefined. When it is passed to the myFunc
function, the property b
is attempted to be accessed. Since a
is undefined at that point, running the code causes the following error:
TypeError: Cannot read properties of undefined (reading 'b')
How to Avoid TypeError: Cannot Read Property of Undefined
When such an error is encountered, it should be ensured that the variable causing the error is assigned a value:
function myFunc(a) {
console.log(a.b);
}
var myVar = {
b: 'myProperty'
};
myFunc(myVar);
In the above example, the myVar
variable is initialized as an object with a property b
that is a string. The above code runs successfully and produces the following output on the browser console:
myProperty
To avoid coming across situations where undefined variables may be accessed accidentally, an if
check should be added before dealing with such variables:
if (myVar !== undefined) {
...
}
if (typeof(myVar) !== 'undefined') {
...
}
Updating the previous example to include an if
check:
function myFunc(a) {
if (a !== undefined) {
console.log(a.b);
}
}
var myVar;
myFunc(myVar);
Running the above code avoids the error since the property b
is only accessed if a
is not undefined
.
Here is how you can handle errors using a try { } catch (e) { }
block.
// Caught errors
try {
//Place your code inside this try, catch block
//Any error can now be caught and managed
} catch (e) {
Rollbar.error("Something went wrong", e);
console.log("Something went wrong", e);
}
In addition to the methods above, modern JavaScript provides two other techniques to handle potential undefined values:
Optional Chaining (ES2020+)
Optional chaining allows you to safely access nested object properties, even if an intermediate property doesn't exist:
function myFunc(a) {
console.log(a?.b);
}
let myVar;
myFunc(myVar); // Logs: undefined (instead of throwing an error)
myVar = { b: 'myProperty' };
myFunc(myVar); // Logs: myProperty
This approach is particularly useful for deeply nested properties:
const user = {};
console.log(user.address?.street); // undefined
console.log(user.address?.street?.name); // undefined
Providing Default Values
You can use the OR operator (||) or the nullish coalescing operator (??) to provide default values:
function greet(name) {
// Use OR operator (||) for falsy values (undefined, null, '', 0, false)
console.log(Hello, ${name || 'Guest'}!
);
// Use nullish coalescing operator (??) for null or undefined only
console.log(Welcome, ${name ?? 'Anonymous'}!
);
}
greet(); // Logs: "Hello, Guest!" and "Welcome, Anonymous!"
greet('Alice'); // Logs: "Hello, Alice!" and "Welcome, Alice!"
These two methods provide more concise ways to handle potential undefined values, making your code more robust and easier to read.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!