Open In App

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

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:

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.




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

Output
2
Article Tags :