Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

JavaScript Array findIndex() method

Reference for JavaScript Array findIndex(): get the index of the first element that passes a test, or -1, with callback arguments and common patterns.

The findIndex() method returns the index of the first element for which your callback returns a truthy value, or -1 if no element passes. Like find(), it stops at the first match.

It is the right choice when you need to know where something is, for example to replace or remove it, or when the array might contain undefined and a plain find() result would be ambiguous.

JavaScript
["a", "b", "c"].findIndex((x) => x === "b"); // 1

Try it

JS Index of a match

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Remove by index and the -1 trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
findIndex(callbackFn)
findIndex(callbackFn, thisArg)
Name Description
callbackFn Called as callbackFn(element, index, array). Return a truthy value for the element you are looking for.
thisArg Optional. Value used as this inside callbackFn (ignored by arrow functions).

Return value: the index (a number from 0) of the first element that passed, or -1 if none did.

Exceptions: a TypeError if callbackFn is not a function.

Usage notes

  • Check for -1 before using the index. The second example shows why: splice(-1, 1) does not do nothing, it removes the last element.
  • Truthiness is enough. The callback result does not have to be exactly true.
  • Reliable with undefined. An element equal to undefined is found at its real index, unlike find(), which would return undefined either way.
  • Holes are visited as undefined, unlike indexOf() and some(), which skip them.
  • Value or condition? indexOf(value) uses strict equality for a plain value. findIndex() is for conditions, and the only choice for objects matched by a property or for NaN (arr.findIndex(Number.isNaN)).
  • From the end: findLastIndex() searches from the last element.
  • Immutable updates: pair it with with() or spread to replace an element without mutating: arr.with(i, newValue).

Browser support

findIndex() is supported in every current browser.