How to Fix the “Cannot read property ‘0’ of undefined” Error in JavaScript

The “cannot read property ‘0’ of undefined” error occurs when you try to access the 0 index of an array-like variable, but the variable turns out to be undefined. To fix it, initialize the variable to a value of the correct data type before accessing the index.

The "cannot read property '0' of undefined" error occuring in JavaScript.

Depending on your scenario, you might be able to resolve the error by doing one of the following:

  1. Provide a defined fallback value for the variable.
  2. Ensure that the variable has been initialized.
  3. If accessing an index of a nested array, check that none of the outer arrays are undefined.

We’ll be touching on these three solutions in this article.

1. Provide defined fallback value

We can fix the “cannot read property ‘0’ of undefined” error in JavaScript by giving the variable a fallback value before accessing it at a specific index. This solution is beneficial when accessing an array property of an object that might return a value of undefined.

We can provide a fallback value with the null coalescing operator (??):

// 👇 Initialize to empty array if undefined
const books = library.books ?? [];

const firstBook = books[0];

console.log(library.books); // undefined

console.log(firstBook); // undefined

// Initialize to empty string if undefined
const content = firstBook ?? '';

console.log(content); // '' (empty string)

The nullish coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(2 ?? 5); // 2
console.log(undefined ?? 5); // 5

We can use the logical OR (||) operator to replace ??:

console.log(2 || 5); // 2
console.log(undefined || 5); // 5

2. Ensure variable initialization

The “cannot read property ‘0’ of undefined” error in JavaScript will occur when you access the 0 index of a variable that is uninitialized. Unintialized variables in JavaScript have a default value of undefined.

let arr;

console.log(arr); // undefined

// ❌ Cannot read properties of undefined (reading '0')
console.log(arr[0]);

const str;

// ❌ Cannot read properties of undefined (reading '0')
console.log(str[0]);

Fixing the error in this case is easy; just set the variable to a value, e.g., an empty array ([]) for arrays, an empty string ('') for strings, etc.

let arr = [];

console.log(arr); // []

// ✅ No error
console.log(arr[0]); // undefined

const str = '';

// ✅ No error
console.log(str[0]); // undefined

3. Check outer arrays for undefined

The “cannot read property ‘0’ of undefined” error can also occur when accessing the 0 index in nested arrays.

const arr = [[1, 2, 3]];

// ❌ Cannot read properties of undefined (reading '0')
console.log(arr[1][0]);

The array here contains only one element, so accessing the 1 index returns undefined. Accessing the 0 index on undefined then causes the error.

The optional chaining operator is a concise way to prevent this error:

const arr = [[1, 2, 3]];

// ✅ No error
console.log(arr?.[1]?.[0]); // undefined

For nullish values (undefined or null), the optional chaining operator (?.) returns undefined instead of trying to access the property and causing an error.

Since the 1 index of the outer array returned undefined, the optional chaining operator will prevent the property access.

If the value is not nullish, the ?. operator will perform the property access:

const words = [['javascript']];

console.log(words?.[0]?.[0]); // javascript

console.log(words?.[0]?.[0]?.[0]); // j


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

2 thoughts on “How to Fix the “Cannot read property ‘0’ of undefined” Error in JavaScript”

Leave a Comment

Your email address will not be published. Required fields are marked *