[Solved] Cannot read Properties of Undefined in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
6 min

banner

# [Solved] Cannot read Properties of Undefined in JavaScript

The "Cannot read properties of undefined" error occurs for multiple reasons:

  1. Accessing a property on a variable that stores an undefined value.
  2. Accessing a property on a DOM element that doesn't exist.
  3. Inserting the JS script tag above the HTML where the DOM elements are declared.

cannot read property of undefined

Most commonly, the error occurs if you try to access a property on a variable that has a value of undefined.

index.js
const person = undefined; // ⛔️ Cannot read properties of undefined (reading 'name') person.name;

We attempted to access the name property on an undefined value which caused the error.

# Use the optional chaining (?.) operator

Use the optional chaining (?.) operator to check if the variable is not nullish before accessing it.

If the variable is undefined or null, the operator short-circuits instead of throwing an error.

index.js
const person = undefined; // ✅ Using optional chaining console.log(person?.name); // 👉️ undefined console.log(person?.name?.first); // 👉️ undefined // ✅ Using if / else if (person?.name) { console.log(person.name); } else { // 👇️ this runs console.log('person.name not found'); } // ✅ Using logical AND (&&) operator console.log(person && person.name); // 👉️ undefined

use optional chaining operator

The code for this article is available on GitHub

The optional chaining (?.) operator allows us to access a property on an object without throwing an error if the reference is invalid.

Instead of throwing an error, the optional chaining (?.) operator short-circuits returning undefined if the reference is equal to undefined or null.

# Using the Logical AND operator

You can also use the logical AND (&&) operator in a similar way.

index.js
const person = undefined; console.log(person && person.name); // 👉️ undefined // 👇️ undefined console.log(person && person.name && person.name.first);

using logical and operator

The code for this article is available on GitHub

The logical AND (&&) operator doesn't evaluate the value to the right if the value to the left is falsy (e.g. undefined).

You can use the logical AND (&&) operator in a similar way to how the optional chaining (?.) operator is used.

index.js
let person; console.log(person); // 👉️ undefined // ✅ using optional chaining if (person?.address?.country) { console.log(person.address.country); } // ✅ using logical AND (&&) if (person && person.address && person.address.country) { console.log(person.address.country); }

# Accessing an array at an index that doesn't exist

A common source of undefined values is accessing an array at an index that doesn't exist.

Use the optional chaining (?.) operator or the logical AND (&&) operator to make sure the array index exists before accessing the property.

index.js
const arr = []; // ⛔️ Cannot read properties of undefined (reading 'name') console.log(arr[0].name); // ❌ Bad console.log(arr[0]?.name); // ✅ Good console.log(arr[0] && arr[0].name); // ✅ Good

accessing array at index that does not exist

The code for this article is available on GitHub
Accessing an array at an index that doesn't exist returns undefined.

Use the same approach if you have to access nested array elements at indices that might not exist.

index.js
const arr = [['a', 'b', 'c']]; console.log(arr?.[0]); // 👉️ ['a', 'b', 'c'] console.log(arr?.[0]?.[0]); // 👉️ a console.log(arr?.[0]?.[0]?.[1]); // 👉️ undefined console.log(arr?.[0]?.[0]?.[1]?.[0]); // 👉️ undefined

You can also use the optional chaining (?.) operator to provide a value to be returned if the variable or its property returned undefined.

index.js
let person; const name = person?.name ?? 'default'; console.log(name); // 👉️ 'default' const country = person?.address?.country ?? 'default'; console.log(country); // 👉️ 'default'
The person variable stores a value of undefined because we didn't initialize it.

If accessing the name property on the person variable returns undefined, the value to the left of the nullish coalescing (??) operator is returned.

I've written a detailed guide on how to check if an array index exists in JavaScript.

# Provide a fallback value for when the variable stores an undefined value

An alternative way to solve the error is to provide a fallback value if the variable stores a falsy value (e.g. undefined).

index.js
const name = undefined; const result1 = (name ?? 'bobby').toUpperCase(); console.log(result1); // 👉️ BOBBY const obj = undefined; const result2 = (obj ?? {name: 'bobby'}).name; console.log(result2); // 👉️ bobby

provide fallback value for when variable stores undefined

The code for this article is available on GitHub

The nullish coalescing operator (??) returns the value to the right if the value to the left is nullish (null or undefined).

In all other cases, it returns the value to the left.

Another common reason for getting the error is accessing a property on DOM element that doesn't exist.

# Track down where the variable got assigned an undefined value

A variable that has been declared but hasn't been given a value has a value of undefined in JavaScript.

index.js
let employee; console.log(employee); // 👉️ undefined // ⛔️ TypeError: Cannot read properties of undefined (reading 'name') console.log(employee.name);

We declared the employee variable but didn't assign a value to it, so it stores an undefined value.

Instead, initialize the variable when declaring it.

index.js
let employee = {}; console.log(employee.name); // 👉️ undefined

We set the employee variable to an empty object, but you can use any other value that suits your use case, e.g. an empty array [] or an empty string "".

You also get an undefined value when you access an array at an index that doesn't exist.

index.js
let employees = []; console.log(employees[1]); // 👉️ undefined // ⛔️ TypeError: Cannot read properties of undefined (reading 'push') console.log(employees[1].push('a'));

If you need to add an element to the array, call the push() method on the array without accessing it at a specific index.

index.js
let employees = []; employees.push('bobby'); employees.push('hadz'); employees.push('com'); // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(employees);

If you meant to access a property on a specific array element, use the optional chaining operator.

index.js
let employees = ['a', 'b']; const result = employees[100]?.toUpperCase(); console.log(result); // 👉️ undefined

If the array element at the specified index doesn't exist, the optional chaining operator returns undefined instead of throwing an error.

If the error persists, you have to track down where the variable got assigned an undefined value.

A common source of undefined values is assigning the output of a function that doesn't return anything to a variable.

Many built-in methods that mutate an object in place return undefined.

All JavaScript functions that don't return a value return undefined.

You might be accessing an array at an index that doesn't exist or a non-existent property in an object.

# Make sure the DOM elements you are accessing exist

To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists.

The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method.

index.js
const boxes = document.getElementsByClassName('does-not-exist'); console.log(boxes); // [] // ⛔️ Cannot read properties of undefined (reading 'innerHTML') console.log(boxes[0].innerHTML);

Instead, correct the class name and use the optional chaining (?.) operator to check if the DOM element at index 0 contains the property.

index.js
const boxes = document.getElementsByClassName('does-not-exist'); console.log(boxes); // [] // ✅ check for existence of property if (boxes[0]?.innerHTML) { console.log(boxes[0].innerHTML); } else { // 👇️ this runs console.log('element does not exist'); }
The code for this article is available on GitHub

If the element at index 0 contains the innerHTML property, our if block will run, otherwise, the else block is run.

# Insert the JS script tag at the bottom of the body tag

Make sure to insert the JS script tag at the bottom of the body tag.

The JS script tag should be placed after the HTML elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <script src="index.js"></script> <!-- ❌ BAD - SHOULD BE ABOVE SCRIPT TAG ❌ --> <div class="box">Hello</div> </body> </html>

The index.js script tag is run before the div element with a class name of box is declared.

If you try to access the div element in the index.js script, it will not be available, thus causing the error.

index.js
const boxes = document.getElementsByClassName('box'); console.log(boxes); // 👉️ [] // ⛔️ Cannot read properties of undefined (reading 'innerHTML') console.log(boxes[0].innerHTML);

You have to place the JS script at the bottom of the body tag, after the HTML elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Hello</div> <!-- ✅ Good - Script is run after HTML is declared ✅ --> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

Now the div element with class name box is accessible inside of the index.js script.

index.js
const boxes = document.getElementsByClassName('box'); console.log(boxes); console.log(boxes[0].innerHTML); // 👉️ "Hello"
The code for this article is available on GitHub

HTML code is parsed from top to bottom, so the script tag has to be placed at the bottom of the body tag, after all of the DOM elements it needs to access.

# Conclusion

The "Cannot read properties of undefined" error occurs when you try to access a property or a method on a variable that stores an undefined value.

To solve the error, check if the variable is not undefined before accessing the property or method.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.