Table of Contents
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 = undefined2console.log(items[0])
If you run the above code in your browser console, you will get the below 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 = undefined2if (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 = undefined2console.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 = undefined2const 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 type2const str1 = undefined3if (typeof str1 === "string") {4 console.log(str1[0])5}67// Default to empty string8const returnValue = undefined9const str2 = returnValue || ""10console.log(str2[0]) //undefined1112// Optiona chaining13const str3 = undefined14console.log(str3?.[0]) //undefined
Do follow me on twitter where I post developer insights more often!
Leave a Comment