Skip to main content

JavaScript Array findIndex Method (Live Playground)

The findIndex method in JavaScript is used to find the index of the first element in an array that satisfies a provided testing function. If no elements pass the test, it returns -1.

Here's an example:

let numbers = [5, 12, 8, 130, 44];

let foundIndex = numbers.findIndex(function (element) {
return element > 10;
});

console.log(foundIndex);
// Expected output: 1

In this example, numbers.findIndex(function(element) { return element > 10; }) returns the index of the first element in numbers that is greater than 10. In this case, the index is 1 (the second element, 12).

Live Playground, Try it Yourself

If we modify our function to search for an index of a number greater than 200, the findIndex method returns -1:

let numbers = [5, 12, 8, 130, 44];

let foundIndex = numbers.findIndex(function (element) {
return element > 200;
});

console.log(foundIndex);
// Expected output: -1

In this code, numbers.findIndex(function(element) { return element > 200; }) returns -1 because there are no elements in numbers that are greater than 200.

Live Playground, Try it Yourself

The findIndex method is a useful tool to locate the position of a specific element in an array based on some criteria. It's helpful when you need to know the index of an element in an array.

Remember to practice using the findIndex method with your own examples!