How to Avoid Getting "Cannot read property of undefined" in JavaScript

How to Avoid Getting

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

Why does this happen?

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 Playground
let 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! Copy
console.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?

Getting the cannot read property of undefined error inside the console

Get your weekly dose of 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 Webtips

Avoiding errors

To 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 Playground
if (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.

undefined

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

Resources:

Did you find this page helpful?

Get your weekly dose of webtips

📚 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 Webtips

Mentoring

Rocket Launch Your Career

Speed 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:

Courses

Master Astro + SEO

Master Astro + SEO

Learn how to build SEO-driven landing pages Ferenc Almasi • 📚 21 lessons

Master React

Master React

From start to finish Ferenc Almasi • 📚 37 lessons

Master Modern JavaScript

Master Modern JavaScript

Learn how to build projects from scratch Ferenc Almasi • 📚 40 lessons

Recommended

How to Create <a href=Pure Objects in JavaScript" width="1700" height="1000" />

How to Create Pure Objects in JavaScript

Ferenc Almasi • 2021 July 23 • 1 min read

How to Turn Values Into Arrays in JavaScript

How to Turn Values Into Arrays in JavaScript

Ferenc Almasi • 2021 July 23 • 1 min read

How to Loop Number of Times in JavaScript

How to Loop Number of Times in JavaScript

Ferenc Almasi • 2024 February 02 • 3 min read 📚 More Webtips

Get your weekly dose of 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 Webtips

Master JavaScript

Tech, science & coding news

© 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 your weekly dose of 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.