Codectionary / Developer documentation / JavaScript

find(), findIndex(), findLast()

These methods search an array using a test function rather than an exact value, making them ideal for finding objects by a property. find() returns the first matching element (or undefined), findIndex() returns its index (or -1), and findLast()/findLastIndex() search from the end instead.

Syntax

arr.find(item => condition)
arr.findIndex(item => condition)

Examples

find() - Locating an Object by Property

The most common use case: finding a specific object in an array.

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" }
];

const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Bob" }

const notFound = users.find(u => u.id === 99);
console.log(notFound); // undefined

findIndex() - Locating a Position

Getting the index of a match, useful before splice() or update operations.

const numbers = [4, 9, 16, 25, 36];
const index = numbers.findIndex(n => n > 15);
console.log(index); // 2 (the index of 16)

const notFoundIndex = numbers.findIndex(n => n > 100);
console.log(notFoundIndex); // -1

findLast() and findLastIndex()

Searching from the end of the array instead of the beginning.

const numbers = [1, 5, 8, 5, 2];

console.log(numbers.findLast(n => n === 5));      // 5 (the last matching value)
console.log(numbers.findLastIndex(n => n === 5)); // 3 (its index)

Best practices

  • Use find() instead of filter()[0] when you only need the first match - it stops searching as soon as it finds one, which is more efficient
  • Use findIndex() when you need the position for a subsequent operation like splice() or array update
  • Prefer find()/findIndex() over indexOf() when searching by object property rather than exact primitive value
  • Remember find() returns undefined (not -1) when nothing matches - check with a truthy check or === undefined, not === -1

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation