Cannot Read Properties Of Undefined In JavaScript – How To Fix It?

Cannot read Properties of Undefined in JavaScript

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

  1. You are accessing an object that has an undefined data type or has not been assigned a value.


let nothing = undefined;


Error: Cannot read properties of undefined (reading 'name')
  1. You are trying to call a method in the undefined object.


let nothing;


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');


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;



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;




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.

Leave a Reply

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