Cannot read property 'firstIndex' of Undefined in JS

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Cannot read property 'firstIndex' of Undefined #

The "Cannot read property 'findIndex' of undefined" error occurs when the findIndex() method is called on an undefined value. To solve the error, make sure to only call the findIndex method on arrays.

cannot read property findindex of undefined

Here is an example of how the error occurs.

index.js
const arr = undefined; // โ›”๏ธ Cannot read properties of undefined (reading 'findIndex') const result = arr.findIndex(e => e * 2 === 10);

To solve the error, initialize the value to an empty array, or conditionally check that the value is of the correct type before calling the findIndex method.

index.js
const fromDb = undefined; // โœ… Provide empty array fallback value const arr = fromDb || []; // โœ… Using optional chaining ?. const r1 = arr?.findIndex(element => element === 10); console.log(r1); // ๐Ÿ‘‰๏ธ -1 // โœ… Using ternary const r2 = arr ? arr.findIndex(element => element === 10) : []; console.log(r2); // ๐Ÿ‘‰๏ธ -1 // โœ… Using Array.isArray if (Array.isArray(arr)) { const r3 = arr.findIndex(element => element === 10); } else { console.log('arr is not an array'); } // โœ… Provide fallback in Place const r4 = (arr || []).findIndex(element => element === 10);

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

If the value to the left is falsy, the logical OR (||) operator returns the value to the right.

The second example uses the optional chaining (?.) operator to short-circuit instead of throwing an error if the reference is equal to undefined or null.

Note that if the condition implemented by the callback function is not satisfied for any of the array elements, the findIndex method will return -1.

The next example uses a ternary operator, which is very similar to an if/else statement.

If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.

The next example uses the Array.isArray method to check if the value is an array before calling the findIndex method.

The last example uses the logical OR (||) operator to provide a fallback of an empty array right before calling the findIndex method.

Conclusion #

The "Cannot read property 'findIndex' of undefined" error occurs when the findIndex is called on an undefined value.

To solve the error, make sure to only call the method on arrays.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee