“Cannot read properties of undefined” Error In JavaScript – How To fix

Cannot read properties of undefined

The “Cannot read properties of undefined” error often occurs when we try to access a function or property of an undefined type variable. Please follow our tutorial to resolve the issue just by a few simple steps. 

What causes the “Cannot read properties of undefined” error?

Reproduce the “Cannot read properties of undefined” error

Example 1:

var obj_1 = { 
  brand: 'LearnShareIt.com',
  year:  2022,
}

var obj_2;
console.log(typeof obj_2.year);

Output: 

TypeError: Cannot read properties of undefined (reading 'year')

In this example, obj_2 is declared but not initialized, so it is currently undefined. Therefore, when we try to call it, it will give us the Cannot read properties of undefined error. 

Undefined: Undefined variables are variables that have been declared but have not been assigned value to them or have not existed in the program. To check if a variable is undefined or not, we can use typeof:  

typeof operand

Operand: representing the object whose type is to be returned. 

Example 2: 

var num = 10;
var str = 'String';

var obj = {
  name: 'LearnShareIT',
  year: 2022,
  single: true,
}

console.log(typeof num);
console.log(typeof str);
console.log(typeof obj.single);
console.log(typeof obj.gender);

Output:

number
string
boolean
undefined

How to solve the “Cannot read properties of undefined” error?

Solution 1: Assign a value to your variable

The most common cause of this problem is that we forget to assign a value to our variables. Even experienced programmers frequently make this error when dealing with large projects. Therefore, always make sure that your variable has a value.

Fixed code for example 1: 

var obj_1 = { 
  brand: 'LearnShareIt.com',
  year:  2022,
}

var obj_2 = {
  brand: 'WordPress',
  year:  2020,
};

console.log(typeof obj_2.year);

Output:

number

Solution 2: Delete the unnecessary variables

Sometimes, you do not really need that variable, so there is no value to it. But somehow, it was just there when we declared it for testing or something. So, double-check your code to remove any unnecessary variables to avoid errors and make your code cleaner.

Solution 3: Check the type of the variable before accessing it

In some cases, your variable can sometimes accidentally be undefined. To deal with that, you can have an if statement to check it first before using. 

Example: 

if (typeof a !== 'undefined') {
  //code to be executed if true
}

Summary

The “Cannot read properties of undefined” error is one of the most common problems in JavaScript. It often happens when we forget to assign a value to our variable before accessing it. Fortunately, the solutions are straightforward, as we must ensure that all of our variables have value before using them.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *