codedamn logo
codedamn

How to deal with TypeError: Cannot read property

  • Vishnupriya's profile image
    Vishnupriya
    Team codedamn
How to deal with TypeError: Cannot read property

If you code in JavaScript or you are a web developer, then you must have come across the famous Uncaught TypeError: Cannot read property of undefined on your chrome browser. While for Safari users, you might have received the “TypeError: undefined is not an object (evaluating … )” error message on your console. No need to worry, this is a common error which you can get when you try to access or read a property on an undefined object. Another similar case like this exists when you try to do the same thing for a null object.

Why do you get ‘TypeError: Cannot read property’?

In JavaScript, undefined is not considered as an object type. Only object types have properties and one can access properties only if the variable is an object. If you attempt to access the property of undefined then you will get an error.

Related Blog – Types of Error in Javascript

Let us consider an object which has been declared but not initialized, due to this the value of the object will be undefined until we define it to some value. Now if we make a request for a property of this undefined object we are bound to fail, as this object has no properties to read. Due to this, we get a Type Error stating we can not read the property of an undefined object.

var user;
console.log(user.id);

How to deal with it?

It is very simple to avoid such errors, first, you need to make sure that you have defined all the variables you have declared. This can be done in different methods. You can either make use of if statements or try and catch blocks, as shown below:

if(typeof(object) === 'undefined' ){
//....
}

One can also make use of the logical OR operator. While assigning a value to a variable you can do the following:

// Assign a fallback while declaring
username = getDetails(name) || {};
// Assign a fallback at return
const getDetails = name => {
// ...
return userResponse || {};
}

Hope this helps you understand what is the meaning of Uncaught TypeError: Cannot read property of undefined and different ways to debug the error if you come across it while coding.

User avatar