Solve - find is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - find is not a function Error in JavaScript #

The "find is not a function" error occurs when we call the find() method on a value that is not of type array. To solve the error, convert the value to an array before calling the find method or make sure to only call the method on arrays.

typeerror find is not a function

Here is an example of how the error occurs.

index.js
const arr = {}; // โ›”๏ธ Uncaught TypeError: arr.find is not a function const result = arr.find(num => num % 2 === 0);

We called the Array.find method on an object and got the error back.

To solve the error, console.log the value you're calling the find method on and make sure it's a valid array.

index.js
const arr = [3, 6, 10]; const result = arr.find(num => num % 2 === 0); console.log(result); // ๐Ÿ‘‰๏ธ 6

Alternatively, you can check if the value is an array by using the Array.isArray method.

index.js
const arr = null; const result = Array.isArray(arr) ? arr.find(num => num % 2 === 0) : 0; console.log(result); // ๐Ÿ‘‰๏ธ 0

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 find method on it, otherwise we return the number 0. This way, you won't get an error, even if the value is not an array.

If the value is fetched from a remote server, make sure it is of the type you expect it to be by logging it to the console and make sure you have parsed it to a native JavaScript array before calling the find method on it.

If you have an array-like object which you're trying to convert to an array before calling the find method, use the Array.from method.

index.js
const set = new Set([13, 2, 3]); const result = Array.from(set).find(element => element % 2 === 0); console.log(result); // ๐Ÿ‘‰๏ธ 2

Before calling the find method, we convert the value to an array.

You could also use the spread syntax (...) to achieve the same result.

index.js
const set = new Set([13, 2, 3]); const result = [...set].find(element => element % 2 === 0); console.log(result); // ๐Ÿ‘‰๏ธ 2

If the error persists, console.log the value you're calling the find method on and make sure it's an array.

If the value is an object, you should probably be accessing a specific property on it, which has a value of an array.

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