Last updated: Mar 3, 2024
Reading time·6 min
The "Cannot read properties of undefined" error occurs for multiple reasons:
undefined
value.Most commonly, the error occurs if you try to access a property on a variable
that has a value of undefined
.
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 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.
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
The optional chaining (?.) operator allows us to access a property on an object without throwing an error if the reference is invalid.
undefined
if the reference is equal to undefined
or null
.You can also use the logical AND (&&) operator in a similar way.
const person = undefined; console.log(person && person.name); // 👉️ undefined // 👇️ undefined console.log(person && person.name && person.name.first);
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.
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); }
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.
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
undefined
.Use the same approach if you have to access nested array elements at indices that might not exist.
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
.
let person; const name = person?.name ?? 'default'; console.log(name); // 👉️ 'default' const country = person?.address?.country ?? 'default'; console.log(country); // 👉️ 'default'
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.
An alternative way to solve the error is to provide a fallback value if the
variable stores a falsy value (e.g. undefined
).
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
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.
undefined
valueA variable that has been declared but hasn't been given a value has a value of
undefined
in JavaScript.
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.
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.
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.
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.
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.
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.
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.
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.
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'); }
If the element at index 0
contains the innerHTML
property, our if
block
will run, otherwise, the else
block is run.
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.
<!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.
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.
<!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>
Now the div element with class name box
is accessible inside of the index.js
script.
const boxes = document.getElementsByClassName('box'); console.log(boxes); console.log(boxes[0].innerHTML); // 👉️ "Hello"
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.
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.
You can learn more about the related topics by checking out the following tutorials: