![]() |
VOOZH | about |
The findIndex() method in JavaScript is a powerful tool for locating the first element in an array that satisfies a provided testing function. This guide provides a comprehensive overview of how to use findIndex() effectively, enhancing your ability to manipulate arrays.
Syntax
array.findIndex(function(currentValue, index, arr), thisValue);Parameters
| Parameter | Description |
|---|---|
| function | The function of the array that operates on each element. |
| currentValue | Holds the current element during iteration. |
| index | (Optional) Index of the current element. |
| arr | (Optional) The array object to which the current element belongs. |
| thisValue | (Optional) Value to be passed as the "this" value to the function. If not provided, defaults to "undefined". |
Return value
It returns the array element index if any of the elements in the array pass the test, otherwise, it returns -1.
Here, the method findIndex() finds all the indices that contain odd numbers. Since no odd numbers are present therefore it returns -1 .
-1
Here, the method findIndex() finds all the indices that contain positive numbers. Since 0.30 is a positive number therefore it returns its index.
2
Here, the method findIndex() finds all the indices that contain numbers greater than 25. Since 30 is greater than 25 therefore it returns its index.
2
Here, the method findIndex() finds all the indices that contain prime numbers.
-1 2
While specific examples will be detailed in the approaches section, here’s a brief overview:
Mastering the findIndex() method enhances your ability to work with arrays efficiently. This guide introduces the importance and prerequisites, setting the stage for detailed method explanations. By focusing on practical applications, you can improve your JavaScript skills and code effectiveness.
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.