JavaScript Array findIndex()

The findIndex() method returns the index of the first array element that satisfies the provided test function or else returns -1.

Example


findIndex() Syntax

The syntax of the findIndex() method is:

arr.findIndex(callback(element, index, arr),thisArg)

Here, arr is an array.


findIndex() Parameters

The findIndex() method can take two parameters:

  • callback - Function to execute on each element of the array. It takes in:
    • element - The current element of array.
  • thisArg (optional) - Object to use as this inside callback.

findIndex() Return Value

  • Returns the index of the first element in the array that satisfies the given function.
  • Returns -1 if none of the elements satisfy the function.

Example 1: Using findIndex() method

Output

2

In the above example, we have used the findIndex() method to find the index of the first even number in the numbers array.

isEven() is a function that returns an even number. We have passed isEven() as a callback in the findIndex() method as- numbers.findIndex(isEven).

The method returns 2 which is the index of the first even number in numbers i.e. 8.


Example 2: findIndex() with Arrow Function

Output

1

Here we have passed an arrow function as a callback in the findIndex() method. The method returns the first index of 'Wednesday'.


Example 3: findIndex() with Object Elements

Output

2

Recommended Reading: JavaScript Array find()