Skip to content
javascript

How to fix "Cannot read properties of undefined (reading '0')" error in JavaScript

Jun 27, 2022Abhishek EH2 Min Read
How to fix "Cannot read properties of undefined (reading '0')" error in JavaScript

If you are accessing arrays you might have come across the following error:

Uncaught TypeError: Cannot read properties of undefined (reading '0')

This issue usually occurs when you are trying to access an element in the array and the array does not contain elements, instead has a value undefined.

Replicating the issue

First, let's replicate the issue.

1const items = undefined
2console.log(items[0])

If you run the above code in your browser console, you will get the below error:

Cannot read properties of undefined error

Now you would ask why would anyone set a variable to undefined and then access [0]? The above code is just for demonstration. There could be scenarios where we are accessing the index of a value returned from a function.

The fix

There are multiple ways we can fix this issue.

Fix 1

The first fix would be to check if the variable is an array as shown below:

1const items = undefined
2if (Array.isArray(items)) {
3 console.log(items[0])
4}

Fix 2

We can use the optional chaining operator (?.) to check if the variable is defined, and only if defined, access the index:

1const items = undefined
2console.log(items?.[0]) //undefined

The above code will print undefined and will not throw any error.

Fix 3

We can also set a default value using logical OR operator, so that the code doesn't break.

1const returnValue = undefined
2const items = returnValue || []
3console.log(items[0]) // undefined

In the above code, if the returned value is undefined (or any other falsy value), it will assign an empty array to items.

Handling in case of strings

If you are trying to access the index of a string instead of an array, you will get the same error. You can use similar solutions in this case.

1// Check type
2const str1 = undefined
3if (typeof str1 === "string") {
4 console.log(str1[0])
5}
6
7// Default to empty string
8const returnValue = undefined
9const str2 = returnValue || ""
10console.log(str2[0]) //undefined
11
12// Optiona chaining
13const str3 = undefined
14console.log(str3?.[0]) //undefined

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com