Sometimes the biggest disappointment in programming is a runtime error. You spent the last few hours writing what you thought to be perfect, error-free code. No red underlining to be found in any of your work so you run it and... something just isn’t working quite right. You check the console and see TypeError: Cannot read properties of undefined (reading '0')
. What’s going on here?
Chances are you are either using an array, a string, or an object literal in your code that you’ve attempted to index using [0]
. These three objects can be used very differently but share the ability to have their contents accessed by using []
. For example:
const arr = ["foo", "bar"];
const str = "foo";
const obj = {
0: "foo",
1: "bar",
};
console.log(arr[0]); // 'foo
console.log(str[0]); // 'f'
console.log(obj[0]); // 'foo'
Code language: JavaScript (javascript)
So why are you getting the TypeError
mentioned above? You have most likely attempted to access your variable’s contents while that variable has no value. Fortunately there are a few easy ways to fix this and prevent it from occurring unpredictably in the future.
To resolve your TypeError: Cannot read properties of undefined (reading '0')
, go through these steps:
undefined
undefined
It happens to the best of us. Double check your code and make sure that the array, string, or object literal you are trying to access is the one you expect to be a properly defined variable.
const arr = [];
const elem = arr[0]; // this is fine
console.log(elem[0]); // ❌ this will cause an error. maybe you just meant "elem"?
Code language: JavaScript (javascript)
Simple mistypes like this are a common mistake that any good developer will admit they have. Sometimes it helps to just take a second glance at your code or read it out loud and suddenly the problem will feel obvious to you. Maybe you could use a rubber duck?
Rubber duck debugging is something that programmers use frequently, often by accident. While reading or speaking through your code you will often come across the solution just by going through it like that, often with a coworker or an inanimate object like a rubber duck. If you work from home like me, that might mean discussing arrays with your pets.
undefined
before using itTo avoid running into this error you can simply check if your variable is undefined
when you want to use it:
let arr;
if (arr) {
arr[0] = "foo";
} else {
arr = ["bar"];
}
console.log(arr[0]); // 'bar'
Code language: JavaScript (javascript)
This is a decent solution because it will guarantee that you do not get the error at runtime which might cause problems elsewhere in the program. That being said, there may be a cleaner solution especially if you do not want to have a bunch of extra if
logic throughout your code.
With the help of the nullish coalescing operator ??
(ES2020+) you can perform logic similar to the above example in line. The syntax for using this operator looks like console.log(a ?? b)
which will log the value of b
if the value of a
is null
or undefined
. If you need to use an earlier version of JavaScript, you may replace ??
with ||
in this scenario.
const arr = undefined;
const str = undefined;
const obj = undefined;
const firstElement = (arr ?? [])[0];
const firstCharacter = (str ?? "")[0];
const zeroProperty = (obj ?? {})[0];
console.log(firstElement); // undefined, no error
console.log(firstCharacter); // undefined, no error
console.log(zeroProperty); // undefined, no error
Code language: JavaScript (javascript)
In the above example, we are using []
, ''
, and {}
as the default values for arrays, strings, and literal objects, respectively. It can be good practice to always check if a variable is undefined
before attempting to access its contents to protect your code from unexpected runtime errors. As a less contrived example, imagine you are using a book API and trying to retrieve a list of books. In this situation you likely have no control over what the data the API sends will look like so it is worth it to add some code to safely access its contents.
function getBooksFromApi() {
// arbitrary API logic that can possibly return undefined
}
const books = getBooksFromApi() ?? [];
console.log(books[0]); // undefined, no error
Code language: JavaScript (javascript)
Whether you are working with JavaScript arrays, strings, or object literals, it is not uncommon to run into an error while trying to access their contents at run time. Runtime errors can be particularly pesky so it is good practice to write some extra code before accessing this type of data’s contents, especially if you have reason to suspect the data could be undefined (if the data is coming from an API, for example). If you have any questions about the solutions given or recommendations for better ways to handle this scenario, feel free to leave a comment below!