“Cannot read properties of undefined in JavaScript” means JavaScript cannot read the properties of an object that you have not defined before. Let’s follow the article below to figure out how to solve this problem.
Common causes of the error “cannot read properties of undefined” in JavaScript
There are many causes of this problem, but the main cause is that JS can’t read the property of the object that stores the undefined value or the object is uninitialized.
Some cases cause this error:
- You are accessing an object that has an undefined data type or has not been assigned a value.
Example:
let nothing = undefined;
console.log(nothing.name);
Output:
Error: Cannot read properties of undefined (reading 'name')
- You are trying to call a method in the undefined object.
Example:
let nothing;
console.log(nothing.toString());
Output:
Error: Cannot read properties of undefined (reading 'toString')
Solutions for this error
Solution 1: Make sure the variable is not an undefined object before using it
Using the if
statement, you can easily check whether the variable is undefined.
let h1 = 'LearnshareIT';
if (h1) {
console.log('h1 is not an undefined object');
}
Output:
h1 is not an undefined object
Write code in the block scope of the if
statement to avoid the error.
Solution 2: Set the default value before reading the properties
You can set the default value for any variables with the nullish coalescing operator ??
as long as the default value cannot be null
or undefined
.
const defaultObj = {
heading: 'LearnshareIT',
};
let h1 = undefined;
let heading = h1 ?? defaultObj.heading;
console.log(heading);
Output:
LearnshareIT
Now, you can read any properties of the heading
object and never get the “cannot read properties of undefined in JavaScript” error.
Solution 3: Using optional chaining (?.
)
Optional chaining accesses the property or method of an object. If the object is undefined or the property does not exist, it returns undefined instead of throwing an error. Therefore, using optional chaining can help us avoid the error.
let h1 = {
content: 'LearnshareIT',
style: {
color: 'grey',
font: 'Lato',
},
};
let h2;
console.log(h1?.style?.color);
console.log(h2?.content);
Output:
grey
undefined
Summary
The “cannot read properties of undefined” error in JavaScript is very common when building web applications. However, by understanding the nature of the problem, we can avoid them easily. Thanks for reading, and I hope this post helps you avoid mistakes.

Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java