How to deal with TypeError: Cannot read property

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;

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.

Become The Best JavaScript Developer 🚀
Codedamn is the best place to become a proficient developer. Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.

Unlimited access to all platform courses

100+ practice projects included

ChatGPT Based Instant AI Help

Structured Full-Stack Web Developer Roadmap To Get A Job

Exclusive community for events, workshops

Create A Free Account

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.


No comments so far