Last updated: Mar 3, 2024
Reading time·4 min
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.
Here is an example of how the error occurs.
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.
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
.
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
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.
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.
A variable that has been declared but hasn't been given a value has a value of
undefined
in JavaScript.
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.
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
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 ""
.
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
.
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
.
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.
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
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.
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.
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.
// ✅ 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'); }
If the arr
variable stores an array, the if
block runs where we access the
array at index 0
, otherwise, the else
block runs.
You can also use the ternary operator to solve the error.
// ✅ 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 ternary operator is
very similar to an if/else
statement.
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.
undefined
valueIf the error persists, you have to track down where the variable got assigned an
undefined
value.
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.