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.
Depending on your scenario, you might be able to resolve the error by doing one of the following:
- Provide a defined fallback value for the variable.
- Ensure that the variable has been initialized.
- If accessing an index of a nested array, check that none of the outer arrays are
We’ll be touching on these three solutions in this article.
1. Provide defined fallback value
We can provide a fallback value with the null coalescing operator (
// 👇 Initialize to empty array if undefined const books = library.books ?? ; const firstBook = books; 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
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
default value of
let arr; console.log(arr); // undefined // ❌ Cannot read properties of undefined (reading '0') console.log(arr); const str; // ❌ Cannot read properties of undefined (reading '0') console.log(str);
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); // undefined const str = ''; // ✅ No error console.log(str); // undefined
3. Check outer arrays for
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);
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?.?.); // undefined
For nullish values (
null), the optional chaining operator (
undefined instead of trying to access the property and causing an error.
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:
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.