One of the most common type errors in JavaScript is the famous "Cannot read property of undefined". This error occurs when you try to read or access a property on an object that is undefined . Another common case that is caused by a similar issue, is when you get the same error message, but with null instead of undefined .
Cannot read property of null
Imagine the following situation. You have a user object that is initially undefined , and it is populated through a fetch request. Your server is down and so it returns with an undefined value, but you didn't handle this failure path, and you still try to read properties from the user object:
Copied to clipboard! Copy Playgroundlet user; // The variable is set to undefined user = await getUser(id); // The request fails and returns `undefined`, but it is not handled console.log(user.name); // You try to log the `name` property of the `user` object, that is still `undefined`
The variable in the code example above is declared, but its value is still set to undefined . Here you are essentially trying to do the following:
Copied to clipboard! Copyconsole.log(undefined.name); // This will throw "Cannot read property 'name' of undefined" // Same as if the request returns with a `null` and you try to read properties from that console.log(null.name); // This will throw "Cannot read property 'name' of null"
Since undefined is not an object, you will get a TypeError , like the one below. So how can we avoid this?
Get access to 300+ webtips 💌
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don't spam. Unsubscribe anytime.
Get Access to WebtipsTo avoid getting these types of errors, we need to make sure that the variables we are trying to read do have the correct value. This can be done in various ways. We can do if checks before dealing with objects whose values are bound to change:
Copied to clipboard! Copy Playgroundif (user !== undefined) // Here `user` is surely not `undefined` > if (typeof(user) !== 'undefined') // We can also use the `typeof` operator >
A much cleaner solution however is to use the logical OR operator, when you assign a value to a variable, or even better, when you return the value from the function:
Copied to clipboard! Copy Playground// Assign a fallback during declaration user = getUser(id) || >; // Assign a fallback during return const getUser = id => . return userResponse || >; >;
If getUser returns undefined or null , then we can fall back to an empty object, and assign that to the user variable. This way, if we try to access user.name , we will get undefined , as we don't have that property on the user object, but we still have an object to work with, so we don't get an error. We can also use TypeScript to easily spot these types of mistakes right inside our IDE.
50 JavaScript Interview Questions And their answers explained Here are 50 JavaScript interview questions that often come up during a technical interview. In one place, one resource to learn from. Learn More
📚 More Webtips
Get access to 300+ webtips 💌Level up your skills and master the art of frontend development with bite-sized tutorials.
We don't spam. Unsubscribe anytime.
Get Access to WebtipsSpeed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:
Pure Objects in JavaScript" width="1700" height="1000" />
Get access to 300+ webtips 💌
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don't spam. Unsubscribe anytime.
Get Access to Webtips © 2020–2024 Webtips. All Rights Reserved.This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.
Decline Accept Get access to 300+ webtips 💌Level up your skills and master the art of frontend development with bite-sized tutorials.
We don't spam. Unsubscribe anytime.