Borislav Hadzhiev
Tue Oct 19 2021·3 min read
Photo by Sergey Svechnikov
The "Cannot set property '0' of undefined" error occurs when trying to set a
value at index 0
on a variable that stores an undefined
value. To solve the
error, make sure that the variable is an array before setting the value at the
specific index.
Here's an example of how the error occurs.
const arr1 = undefined; // ⛔️ Cannot set properties of undefined (setting '0') arr1[0] = 'first'; const arr2 = []; // ⛔️ Cannot set properties of undefined (setting '0') arr2[0][0] = 'nested first';
The first example tries to set the element at index 0
of an undefined
value,
which causes the error.
undefined
value back. In the second example, arr2[0]
, returns undefined
, and trying to set the element at index 0
of undefined
throws the error.To solve the error check if the variable stores an array, before setting the value at the specific index.
const fromDb = undefined; // 👇️ With One Dimensional Arrays // ✅ Provide empty array fallback value const arr1 = fromDb || []; if (Array.isArray(arr1)) { arr1[0] = 'first'; } // 👇️ with Two Dimensional Arrays const arr2 = []; if (Array.isArray(arr2[0])) { arr2[0][0] = 'nested value'; } else { arr2[0] = ['nested value']; } console.log(arr2); // 👉️ [ ['nested value'] ]
The first example shows how to use the logical OR (||) operator to provide a
fallback value if the value to the left is falsy (e.g. undefined
).
Array.isArray
method to check if the variable stores an array, before setting the value at the specific index.The second example does the same, but for two dimensional arrays.
If the value at index 0
is an array, we set the nested index to a specific
value, otherwise we initialize the index to an array containing the value.
Alternatively, you could use the logical AND (&&) operator instead of the
Array.isArray
method.
const fromDb = undefined; // ✅ Provide empty array fallback value const arr1 = fromDb || []; if (arr1) { arr1[0] = 'first'; } // ✅ with Two Dimensional Arrays const arr2 = []; if (arr2 && arr2[0]) { arr2[0][0] = 'nested value'; } else { arr2[0] = ['nested value']; } console.log(arr2); // 👉️ [ ['nested value'] ]
The if
statement in the first example checks if the arr1
variable stores a
truthy value. Truthy are all the values that are not falsy.
The falsy values in JavaScript are: undefined
, null
, false
, 0
, ""
(empty string), NaN
.
If the arr1
variable stores any other than the aforementioned 6
values, the
if
block will run.
The second example uses the logical AND (&&) operator. The values to the left
and right of the operator have to be truthy for the if
block to run.
Array.isArray
because it explicitly checks if the variable stores an array before setting a value at a specific index.The "Cannot set property '0' of undefined" error occurs when trying to set the
0th index of a variable that stores an undefined
value.
To solve the error, make sure that the variable on which you are setting the index stores an array.