Array’s find & findIndex Why, How & Polyfill

Bhavesh Kumar Jain
2 min readJul 5, 2020

WHY :

In older versions of Javascript i.e. before ES6 we need to write lots of cumbersome code & for loops to find the particular element or it’s index from the array. But in ES6, we do have find & findIndex methods using which we can find the element and it’s index.

Couple of Scenarios where we can use find & findIndex are :
1. To see/edit the details of a movie from the List of Movies which are displayed on UI. Here find() can be used to get that particular movie data.
2. Replacing specific data of a record from the List of records. Here we can use findIndex() and update data using that index.

HOW :

find() method will return the first element from the array which satisfies the callback testing function, If no elements matches then undefined will be returned.
e.g. : If we want to find a Negative number from an array of numbers we can use find(). Even if array has many negative numbers, the first negative number which satisfies the callback function will be returned as seen in the example

[10,2,3,6,-1,8, -10, 7,9,-20].find(num => num < 0) === “-1”

Similar to find(), findIndex() method will return the index of the first element from the array which satisfies the callback testing function, If none of the elements matches then -1 will be returned.
e.g. : If we want to find the index of the Negative number which is greater than -9 then we can use findIndex().

[10,6,-1, -10, 7,9,-20].findIndex(num => num < 0 && num > -9) === “3”

NOTE : findIndex will be more useful to find the Index of the Object from Array of Objects.

POLYFILLS :

Both find & findIndex are ES6 methods so these are not supported in older browsers like IE8, IE9 etc, we can use polyfill for this purpose.
Polyfill for Array.find(). (Github)

Find Polyfill

Polyfill for Array.findIndex(). (Github)

Find Index Polyfill

Thanks for reading.

--

--