Cannot read properties of undefined (reading '0') in JS

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
4 min

banner

# Cannot read properties of undefined (reading '0') in JS

The "Cannot read properties of undefined (reading '0')" error occurs when accessing an undefined value at index 0.

To solve the error, initialize the variable to the correct data type, e.g. an array or a string, before accessing the index.

cannot read property 0 of undefined

Here is an example of how the error occurs.

index.js
const arr = undefined; // ⛔️ TypeError: Cannot read properties of undefined (reading '0') console.log(arr[0]);

Attempting to access an undefined value at an index of 0 causes the error.

# Provide a fallback value when the variable is undefined

One way to solve the error is to use the logical OR (||) operator to initialize the variable to an empty array or string if it's undefined.

index.js
const fromDb = undefined; // ✅ fallback value of an empty array const employees = fromDb || []; const firstEmp = employees[0]; console.log(firstEmp); // 👉️ undefined // -------------------------------------- // ✅ fallback value of an empty string const emps = fromDb || ''; const first = emps[0]; console.log(first); // 👉️ undefined

provide fallback value when variable is undefined

The code for this article is available on GitHub

The logical OR (||) operator returns the value to the right if the value to the left is falsy (e.g. undefined).

You can also provide a fallback of an empty array or string right before accessing the value at an index.

index.js
const employees = undefined; const firstEmp = (employees || [])[0]; console.log(firstEmp); // 👉️ undefined

If the employees variable stores a falsy value (e.g. undefined), the expression returns an empty array.

# Make sure the variable has been initialized

A variable that has been declared but hasn't been given a value has a value of undefined in JavaScript.

index.js
let arr; console.log(arr); // 👉️ undefined // ⛔️ TypeError: Cannot read properties of undefined (reading '0') console.log(arr[0]); // ------------------------------------------------- let str; console.log(str); // 👉️ undefined // ⛔️ TypeError: Cannot read properties of undefined (reading '0') console.log(str[0]);

We declared the arr and str variables but didn't assign values to them, so they both store undefined values.

Instead, initialize the variable when declaring it.

index.js
let arr = ['bobby', 'hadz', 'com']; console.log(arr); // 👉️ [ 'bobby', 'hadz', 'com' ] console.log(arr[0]); // 👉️ bobby // ------------------------------------------------ let str = 'abc'; console.log(str); // 👉️ abc console.log(str[0]); // 👉️ a

make sure the variable has been initialized

The code for this article is available on GitHub

We set values for the 2 variables upon declaration which resolved the error.

If you don't have a suitable initial value, set the variable to an empty array [] or an empty string "".

# Solve the error when working with nested arrays

The error also occurs when accessing a nested array at an index that doesn't exist and then accessing the undefined value at index 0.

index.js
const arr = [ ['a', 'b'], ['c', 'd'], ]; // ⛔️ TypeError: Cannot read properties of undefined (reading '0') console.log(arr[2][0]);

We have a two-dimensional array that contains 2 elements.

JavaScript indexes are zero-based, so the last array element has an index of 1.

We tried to access the array at index 2, got an undefined value and tried to access the undefined value at index 0 which caused the error.

Instead, use the optional chaining operator to short-circuit instead of throwing an error.

index.js
const arr = [ ['a', 'b'], ['c', 'd'], ]; console.log(arr?.[0]); // 👉️ ['a', 'b'] console.log(arr?.[0]?.[0]); // 👉️ a console.log(arr?.[0]?.[0]?.[1]); // 👉️ undefined console.log(arr?.[0]?.[1]?.[0]?.[0]); // 👉️ b

use optional chaining operator to short circuit

The code for this article is available on GitHub

The optional chaining (?.) operator short-circuits and returns undefined if the value to the left is nullish (null or undefined).

The optional chaining (?.) operator returns the value if an element with the specified index exists.

index.js
const arr = [['hello']]; console.log(arr?.[0]?.[0]); // 👉️ "hello"

The inner array contains an element at index 0, so the optional chaining operator returned the value.

# Check if the value is of the correct type before accessing it at an index

You can check if a variable stores an array by using the Array.isArray() method.

To check if a variable stores a string, use the typeof operator.

index.js
// ✅ check if a variable stores an array const arr = undefined; if (Array.isArray(arr)) { const first = arr[0]; console.log(first); } else { // 👇️ this runs console.log('The value is NOT an array'); } // ---------------------------------------------- // ✅ check if a variable stores a string const str = undefined; if (typeof str === 'string') { const first = str[0]; console.log(first); } else { // 👇️ this runs console.log('The value is NOT a string'); }
The code for this article is available on GitHub

If the arr variable stores an array, the if block runs where we access the array at index 0, otherwise, the else block runs.

# Use the ternary operator to solve the error

You can also use the ternary operator to solve the error.

index.js
// ✅ with arrays const arr = undefined; const result1 = Array.isArray(arr) ? arr[0] : ''; console.dir(result1); // 👉️ "" // ------------------------------------------- // ✅ with strings const str = undefined; const result2 = typeof str === 'string' ? str[0] : ''; console.dir(result2); // 👉️ ""
The code for this article is available on GitHub

The ternary operator is very similar to an if/else statement.

If the expression before the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise, the value to the right of the colon is returned.

If the value stored in the arr variable is falsy (e.g. undefined), we return an empty string, otherwise, we return the first element in the array.

We used a fallback value of an empty string in the example, but you can use any other value that suits your use case.

# Track down where the variable got assigned an undefined value

If the error persists, you have to track down where the variable got assigned an undefined value.

A common source of undefined values is assigning the output of a function that doesn't return anything to a variable.

Many built-in methods that mutate an object in place return undefined.

All JavaScript functions that don't return a value return undefined.

You might be accessing an array at an index that doesn't exist or a non-existent property in an object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.