find()
ES6+Returns the first element in the array that satisfies the provided testing function.
Syntax
array.find(callback(element, index, array), thisArg)Parameters
callback Function Function to test each element
Return Value
The first element that satisfies the condition, or undefined
Examples
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(x => x > 10);
console.log(found); 📌 When to Use
Use find() when you need to locate a single element in an array based on a condition. It's ideal for looking up items by ID, finding the first match in a list, or checking if a complex object exists with certain properties.
⚠️ Common Mistakes
Forgetting that find() returns undefined (not null) when no element is found
Using find() when you need all matching elements - use filter() instead
Not handling the undefined case when the element might not exist
✅ Best Practices
Use optional chaining or nullish coalescing when accessing properties of the result: arr.find(x => x.id === 1)?.name
For simple value lookups, consider using includes() or indexOf() instead
Combine with destructuring for cleaner code: const { name } = arr.find(...) ?? {}
⚡ Performance Notes
find() stops iterating as soon as it finds a match, making it more efficient than filter()[0] for large arrays. For frequent lookups by ID, consider converting your array to a Map or object for O(1) access time.
🌍 Real World Example
Finding a User by ID in a List
Locate a specific user from an array of users based on their unique ID
const users = [
{id: 1, name: 'Alice', role: 'admin'},
{id: 2, name: 'Bob', role: 'user'},
{id: 3, name: 'Charlie', role: 'user'}
];
const currentUserId = 2;
const currentUser = users.find(user => user.id === currentUserId);
// currentUser: {id: 2, name: 'Bob', role: 'user'}
// Safe access with optional chaining
const userName = users.find(u => u.id === 999)?.name ?? 'Guest';