The findIndex()
method in JavaScript is used to find the index of the first element in an array that satisfies a specified condition. This method returns the index of the first element in the array that passes the test, or -1
if no such element is found.
Here is an example of how the findIndex()
method works:
const array1 = [1, 2, 3, 4, 5];
const result = array1.findIndex(element => element > 3);
// the result will be: 3
In the code example above, we first declare an array called array1
that contains the numbers 1
through 5
. We then use the findIndex()
method to find the index of the first element in the array that is greater than 3
. The findIndex()
method takes a callback function as an argument, and this callback function is called for each element in the array. The callback function should return a Boolean value indicating whether the element satisfies the specified condition. In this case, the callback function simply checks if the element is greater than 3
.
As a result of calling the findIndex()
method, the result
variable will be set to 3
, which is the index of the first element in the array1
array that is greater than 3
. If no element in the array satisfies the specified condition (i.e., if no element is greater than 3
), the result
variable would be set to -1
.
Leave a Reply