Looking a customer up by identifier, the first unpaid order, the row of a table carrying a flag: every time, you are after one item and one only, and you want to stop the moment it turns up.
find does exactly that, where a filter would walk the whole array only to keep one slot.
Definition
find is an Array method handing back the first item the function answered true for, then ending the walk. If no item passes, it hands back undefined.
const customers = [
{ id: 1, email: "ada@site.com" },
{ id: 2, email: "alan@site.com" },
];
console.log(customers.find((c) => c.id === 2).email); // "alan@site.com"
console.log(customers.find((c) => c.id === 99)); // undefinedWhat find hands back is the item itself, not a one-item array. Writing filter(...)[0] gives the same result, but walks everything and builds an intermediate array along the way.
Handling the missing case
The undefined handed back is the most frequent source of errors: reading a property off it throws a TypeError straight away. Two operators are enough to guard against it.
const found = customers.find((c) => c.id === 99);
console.log(found?.email ?? "unknown"); // "unknown"Optional chaining (?.) stops the read when the value is missing, and Nullish coalescing (??) supplies the fallback. Without them an explicit if is needed, which stays preferable when the absence deserves proper handling.
The whole family
| Method | What it hands back | If nothing passes |
|---|---|---|
find | The first item | undefined |
findIndex | The position of the first | -1 |
findLast | The last item | undefined |
indexOf | The position of a value | -1 |
That last row compares with Strict equality (===), which keeps it to simple values: on objects it only finds the exact reference. To search on a criterion, find or findIndex is required.
findLast walks the array from the end, which spares reversing a copy just to reach the last line of a log or the last accepted payment.
Frequently asked questions
How do you tell "not found" from a real undefined value?
That is the limit of find: an array genuinely holding undefined hands back the same thing in both cases. Switch to findIndex, whose -1 cannot be mistaken for a value in the array.
find or Array.some()?
It depends on what you need next. some answers yes or no and is enough for a test, find brings the item back. Both stop on the first success, so the choice comes down to readability, not to speed.
Is there an equivalent on an object?
Not directly, an object not being an array. You go through Object.entries, which hands back an array of key-value pairs, then apply find to the second slot of each pair. On a collection looked up often, a Map structure spares that detour and reaches the entry with no walk at all.