isotropic-2022
Share
Blog
Search
Menu

How To Fix Cannot read Property '0' of Undefined in JS

By Greg Murray
|
Last updated on April 18th, 2022
|

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?

cannot-read-property-0-of-undefined

The Problem

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.

The Solution

To resolve your TypeError: Cannot read properties of undefined (reading '0'), go through these steps:

  1. Ensure you are using the correct variable
  2. Perform a simple check on your variable before using it to make sure it is not undefined
  3. Create a default value for the variable to use if it does happen to be undefined

Ensure you are using the correct variable

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.

Check if the variable is undefined before using it

To 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.

Use a default value when your variable could possibly be undefined

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 errorCode 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 errorCode language: JavaScript (javascript)

Conclusion

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!

The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Article By
Greg Murray
Contributors/Editors
notloggedin
I’m a passionate and driven web developer with an eye for design and appreciation for the human aspect of technology. I am experienced with building websites for small to medium businesses or large web applications for big businesses. Websites can be custom made using cutting edge technology and responsive design or created using the website builder of your choice.
We're looking for new authors. Explore Isotropic Jobs.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram