.findIndex()

christian.dinh's avatar
Published Sep 2, 2021Updated Sep 3, 2021
Contribute to Docs

The .findIndex() array method returns the first index that passes the callback function’s test. Returns -1 if no element passes the test.

Syntax

array.findIndex((element, index, array) => {...});

A function can be invoked with three arguments:

  • element: The current element we are iterating through.
  • index (optional): The index of the array element.
  • array (optional): The array itself.

Examples

Find the first element that satisfies the condition:

const cats = ['Kiki', 'Leo', 'Milo', 'Cleo', 'Lily', 'Luna'];
const findLily = cats.findIndex((cat) => {
return cat == 'Lily';
});
console.log(findLily);
// Output: 4

If no element satisfies the condition, the result will be -1:

const cats = ['Kiki', 'Leo', 'Milo', 'Cleo', 'Luna'];
const findLily = cats.findIndex((cat) => {
return cat == 'Lily';
});
console.log(findLily);
// Output: -1

Codebyte Example

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy