Code highlights logo

Learn

Iterators

The .findIndex() Method

The .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.

How does .findIndex() work?

The syntax for using the .findIndex() method is as follows:

1array.findIndex(callback(element[, index[, array]])[, thisArg])

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.

The .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.

Example:

1const numbers = [10, 20, 30, 40, 50];
2
3const index = numbers.findIndex((num) => num > 30);
4
5console.log(index);
6// Output: 3

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 40.


Instructions

1.

Declare a variable passingScore and assign it the value of 80.

2.

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 passingScore variable.

3.

Print the index value to the console.

Sign up to start coding

Already have an account?

Sign In

Course content