Open In App

What is the use of the Array.findIndex() method in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Array.findIndex() method in JavaScript is used to find the index of the first element in an array that satisfies a provided testing function. It returns the index of the first element for which the testing function returns true. If no such element is found, it returns -1.

Syntax:

array.findIndex(function(currentValue, index, arr), thisValue);

Parameters:

  • function: It is the function of the array that works on each element.
  • currentValue: This parameter holds the current element.
  • index: It is an optional parameter that holds the index of the current element.
  • arr: It is an optional parameter that holds the array object to which the current element belongs.
  • thisValue: This parameter is optional if a value is to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value.

Example: Here, we have an array numbers containing numeric values. We use findIndex() to find the index of the first element that is greater than 25. The callback function checks if each element is greater than 25. The first element that satisfies this condition is 30, which has an index of 2. Therefore, findIndex() returns 2 as the output.

Javascript




const numbers = [10, 20, 30, 40, 50];
 
const index = numbers.findIndex((element) => element > 25);
 
console.log(index);


Output

2

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads