Array.prototype.findIndex()
find, but it hands back the position instead of the element. That makes it the reliable way to distinguish "matched a falsy value" from "matched nothing".
Demo
The index of the first passing element comes back, and iteration stops there. A missing match gives -1, and an empty array gives -1 too. The advantage over find is precision: a result of 0 means "matched at the start" and -1 means "no match", whereas find returns the element itself and cannot distinguish a matched 0 from a failed search.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| callback | Function | yes | Called as callback(element, index, array). Iteration stops at the first truthy result. |
| thisArg | any | no (undefined) | Value of `this` inside the callback. Ignored for arrow functions. |
Return value
number — Index of the first element for which the callback returned truthy, or -1 when none did.
Common patterns
const i = items.findIndex(x => x.id === id); if (i !== -1) items[i] = updated;
const i = items.findIndex(pred); if (i !== -1) items.splice(i, 1);
const i = values.findIndex(v => v === 0); const found = i !== -1;
Examples
Pitfalls
if (items.findIndex(pred)) { /* "found" */ }
if (items.findIndex(pred) !== -1) { ... }
items.findIndex(pred).name
items[items.findIndex(pred)].name
[1, 2, 3].findIndex(x => { x > 1 })
[1, 2, 3].findIndex(x => x > 1)
When to use
- You need the position in order to replace or remove
- Distinguishing a falsy match from no match at all
- Matching by a predicate rather than by value
- You want the element → find
- You are matching a plain value → indexOf
- You only need a yes/no answer → some
Notes
FAQ
findIndex when you need the position — to replace, remove, or to tell a falsy match apart from no match. find when you just want the element and none of its possible values are falsy.