Cannot read property of undefined in JavaScript
The TypeError: “Cannot read property of undefined” occurs when you read a property or a function on an undefined variable or when you try to access a property on a DOM element that doesn't exist. It also occurs when you are accessing an element of an array before it was initialized.
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 an object product
which is undefined. This will cause an error.
To fix the TypeError: cannot read property of undefined, you should check whether the variable is undefined or not. For this 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
.
Access a property on a DOM element that doesn't exist
Take another scenario in which the error occurs when you access a property on a DOM element that doesn't exist. This will result in TypeError: Cannot read property of undefined. Let us take the below example in which an element does not exist with the class name ‘not-existing-class-name’.
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.
Accessing an element of an array before it was initialized
The error “Uncaught TypeError: Cannot read properties of undefined (reading '0')” will also happen when you try to access the array element before it was initialized. Look into the below code.
let products;
console.log(products[0]); // Uncaught TypeError: Cannot read properties of undefined (reading '0')
To fix this issue initialize the array variable before accessing the property.
Solution for error “Cannot read property of undefined” 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:
To solve the “TypeError: Cannot read property of undefined”, use the optional chaining operator on the variable before accessing a property. To avoid the error, make sure you are not accessing a property on a DOM element that doesn't exist. Also, make sure you are not accessing elements in the array variable before it gets initialized.
On datainfinities.com, Read articles all around JavaScript, React, Node.js, PHP, Laravel, and Shopify.
Related Blogs
node: --openssl-legacy-provider is not allowed in NODE_OPTIONS
ERESOLVE unable to resolve dependency tree error when installing npm packages
Find greatest common divisor (GCD) in JavaScript
Remove an item from an array in JavaScript
What are Parameters, Arguments and Arguments Object in JavaScript
How to fix npm ERR! Missing script: "start"
How to Fix error:0308010C:digital envelope routines::unsupported
Pass data from child to parent component in React
Factory Design Pattern in JavaScript
Explore All Blogs