.findIndex() method is particularly useful when we want to find the position of an element that meets a certain criteria. This can be helpful in scenarios such as searching for a specific value, identifying the index of an object with specific properties, or even filtering out unwanted elements from an array.
The syntax for using the
.findIndex() method is as follows:
Here's what each component means:
array: The array that needs to be searched.
callback: A function that is executed on each element of the array. It can take up to three arguments:
element (the current element being processed),
index (the index of the current element being processed), and
array (the array being traversed).
thisArg (optional): An object to which
this can refer to inside the callback function.
.findIndex() method returns the index of the first element in the array that satisfies the provided testing function. If no element matches the criteria, it returns -1.
In this example, we have an array of numbers. We use the
.findIndex() method along with a callback function to find the index of the first number that is greater than 30. The returned index is 3, which corresponds to the element
Declare a variable
passingScore and assign it the value of 80.
Declare a new variable
index that will use the
.findIndex() method on the
students array to find the index of the first student whose
score is greater than or equal to the
index value to the console.
Sign up to start coding
Already have an account?