First Matching Item
find returns the first element that matches the condition.
If nothing matches, it returns undefined.
JavaScript Tutorial
find returns the first item that matches a condition.
It is useful for lookups and searches by id.
Searching lists is common in apps. find makes it simple and efficient.
It stops early, which is faster than filtering everything.
array.find((value, index, array) => condition)const users = [{ id: 1 }, { id: 2 }];
const user = users.find((u) => u.id === 2);
console.log(user);Returns the first user with id 2.
const nums = [1, 2, 3];
const result = nums.find((n) => n > 10);
console.log(result); // undefinedIf nothing matches, you get undefined.
find returns the first element that matches the condition.
If nothing matches, it returns undefined.
find stops searching after the first match.
It is more efficient than filter when you only need one item.
find is great for looking up items by id or key.
Combine with optional chaining for safe access.
const products = [{ sku: "A", price: 10 }];
const item = products.find((p) => p.sku === "B");
const price = item?.price ?? 0;
console.log(price);Use optional chaining to avoid errors.
const names = ["ava", "noah", "liam"];
const result = names.find((n) => n.startsWith("n"));
console.log(result);find works on any array of values.
Without
let found;
for (const u of users) {
if (u.id === 2) {
found = u;
break;
}
}With
const found = users.find((u) => u.id === 2);Use filter when you need all matches.
Check the result or use optional chaining.
Use findIndex if you need the position.
Undefined.
When you only need the first match.
Check the result or use optional chaining.
Practice: Find the first number greater than 50 in an array.
const nums = [10, 60, 40];
// TODO: find first > 50
One Possible Solution
const nums = [10, 60, 40];
const result = nums.find((n) => n > 50);
console.log(result);The first matching element or undefined.
No, it does not change the array.
When you need only the first matching item.
Try searching for different ids.