Cannot read property of undefined in JavaScript

The TypeError: Cannot read property of undefined is one of the most common type errors in JavaScript. It occurs when we try to read a property or a function on an undefined variable or when we try to access a property on a DOM element that doesn't exist.

Let us take an example of the below code:

const product = undefined;
// TypeError: Cannot read properties of undefined (reading 'brand')
console.log(product.brand);

Here we are trying to read a property brand on object product which is undefined.

To fix the TypeError: cannot read property of undefined, we can use the optional chaining operator on the variable before accessing a property. If the variable is undefined or null, the optional chaining operator will return undefined immediately and prevent the property access.

const product = undefined;
console.log(product?.brand); // output: undefined
// This will works for nested property access also
console.log(product?.brand?.name); // output: undefined
// Usage in if/else statements
if (product?.brand) {
  console.log(product.brand);
} else {
  console.log("Can't find 'brand' property in 'product'");
}

The optional chaining (?.) operator allows us to access a property on an object without throwing an error if the reference is invalid. We can use the optional chaining (?.) operator in nested property access as product?.brand?.name

When we access a property on a DOM element that doesn't exist

In another scenario we get the TypeError: Cannot read property of undefined when we access a property on a DOM element that doesn't exist. Let us take the below example:

 const elements = document.getElementsByClassName('not-existing-class-name');
 // TypeError: Cannot read properties of undefined (reading 'innerHTML')
 console.log(boxes[0].innerHTML);

We can solve the error using the optional chain operator inside the if condition as given below example.

const elements = document.getElementsByClassName('not-existing-class-name');
if (elements[0]?.innerHTML) {
	console.log(elements[0].innerHTML);
} 
else {
	console.log('element does not exist');
}

In the above code, If the first index of the elements array contains the innerHTML property, then if block will run otherwise, the else block will run.

Solution for JavaScript before ECMAScript 2020

Here we are using try-catch inside the function. This solution can be used for JavaScript before ECMAScript 2020.

function getSafe(fn, defaultVal) {
  try {
    return fn();
  } catch (e) {
    return defaultVal;
  }
}
// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));
// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));

Output:

undefined
nothing

Conclusion:

The TypeError: Cannot read property of undefined occurs:

  • When we try to read a property on an undefined variable.
  •  When we try to access a property on a DOM element that doesn't exist.

We can use try-catch inside the function if we are using JavaScript before ECMAScript 2020

Related Blogs

Greatest Common Divisor (GCD) in JavaScript

Find greatest common divisor (GCD) in JavaScript

Find the Greatest Common Divisor(GCD) of two numbers using the Euclidean algorithm in javascript. Calculate GCD for a given integer array.

How to Fix error:0308010C:digital envelope routines::unsupported

How to Fix error:0308010C:digital envelope routines::unsupported

To fix the error:0308010C:digital envelope routines::unsupported, enable the legacy provider for Node.js by passing --openssl-legacy-provider flag to webpack.

ckeditor

How to Integrate Custom Build CKEditor5 with React

Explains how to create a custom build CKEditor5 and integrate with react with sample code.

pm2 cluster

Scaling Node.js Applications With PM2 Clusters

Learn cluster modules in node js, install and configure PM2 in production, and implement PM2 clusters using the PM2 ecosystem without any modification in the current application code.

call-stack-in-javascript

What is Call Stack in JavaScript

JavaScript Call Stack is a mechanism to keep track of multiple function calls and manage execution context. This article describes how the call stack works with examples.

Factory Design Pattern in JavaScript

Factory Design Pattern in JavaScript

Factory allows you to handle all the object creation in a centralized location which helps the code clean, concise, and maintainable. Understand deeply with examples.

event loop and callback queue

Event Loop and Callback Queue in JavaScript

The event loop keeps monitoring the call stack and callback queue for executing callback functions. Read more about web APIs, callback queue, microtask queue, event loops, and starvation.

Objects Are Not Valid as a React Child

React objects are not valid as a react child

The React error "Objects are not valid as a React child" occurs when we render an object or an array in our JSX code. We can't use JavaScript objects as a child in React.

Can't Perform a React State Update on an Unmounted Component

Can't Perform a React State Update on an Unmounted Component

React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted. Explains how to fix it.