How to Fix the "Cannot read property '0' of undefined" Error in JavaScript

Last updated on November 14, 2022
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); <em class="">// 2</em>
console.log(undefined ?? 5); <em class="">// 5</em>

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')

const str;

// ❌ Cannot read properties of undefined (reading '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')

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
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also