Learn about the Array findIndex method in JavaScript
2 min readJan 3, 2021
Find an item in an array with the ‘findIndex’ method in JavaScript.
The
findIndex()
method returns the index of the first element of the array if the callback function passed to thefindIndex
method returns true, otherwise returns -1
Syntax
arr.findIndex(callback( element, index, array ) ,thisArg)
callback function
→ A function to execute on each value in the array until the function returnstrue
, indicating that the satisfying element was found.thisArg
→ Optional object to use asthis
when executingcallback
.
The callback function
takes three arguments
element
→ current processing elementindex (Optional)
→ index of the element processingarray (Optional)
→ array in which findIndex method called.
Note
- once the callback returns the index, it will not process the remaining elements.
Unlike other array methods such as Array.some()
, callback
is run even for indexes with unassigned values.
Extras :
The Array.find()
method, which returns the value of an array element, instead of its index.
You can find the implementation details of findIndex
method here.