Borislav Hadzhiev
Wed Oct 20 2021·3 min read
Photo by Azat Satlykov
The "findIndex is not a function" error occurs for multiple reasons:
findIndex
method in a browser that doesn't support it.findIndex
method on a value that is not an array.Here is an example of how the error occurs.
const arr = {}; // ⛔️ TypeError: findIndex is not a function const result = arr.findIndex(element => element % 2 === 0);
We called the Array.findIndex() method on an object and got the error back.
To solve the "findIndex is not a function" error, make sure to only call the
findIndex()
method on arrays and in browsers that support it. The findIndex
method can only be called on arrays and returns the index of the first element
that passes the test.
const arr = [3, 4, 9, 12]; const result = arr.findIndex(element => element % 2 === 0); console.log(result); // 👉️ 1
findIndex
method is not supported in Internet Explorer. If you have to support the browser, you can use the some
method instead.// ✅ Supported in Internet Explorer const arr = [3, 4, 9, 12]; let index = -1; const result = arr.some((element, idx) => { if (element % 2 === 0) { index = idx; return true; } return false; }); console.log(result); // 👉️ true console.log(index); // 👉️ 1
We used the some()
method to implement something similar to the findIndex()
method.
Our solution works in Internet Explorer, but is a bit more verbose.
index
variable, otherwise we simply return false
and keep iterating.You can conditionally check if the value is an array by using the Array.isArray method.
const arr = null; const result = Array.isArray(arr) ? arr.findIndex(element => element % 2 === 0) : -1; console.log(result); // 👉️ -1
We used a ternary operator, which is very similar to an if/else
statement.
If the value is an array, we return the result of calling the findIndex
method
on it, otherwise we return -1
. This way, you won't get an error, even if the
value is not an array.
findIndex
method on it.If you have an array-like object which you're trying to convert to an array
before calling the findIndex
method, use the Array.from
method.
const set = new Set([3, 5, 9, 12]); const result = Array.from(set).findIndex(e => e % 2 === 0); console.log(result); // 👉️ 3
Before calling the findIndex
method, we convert the value to an array.
You could also use the spread syntax (...) to achieve the same result.
const set = new Set([3, 5, 9, 12]); const result = [...set].findIndex(e => e % 2 === 0); console.log(result); // 👉️ 3
If the error persists, console.log
the value you're calling the findIndex
method on and make sure it's an array.