Topic 21 of 37
find, some, every
Overview
When you don't need to transform an array but just want to check its contents, methods like .find(), .some(), and .every() are optimized to stop iterating as soon as they find the answer (short-circuiting), making them much faster than using .filter() for existence checks.
Syntax
Use find to get a single object. Use some/every to get a yes/no answer.
Efficient Searching
javascript
const users = [{ id: 1, admin: true }, { id: 2, admin: false }];
// .find(): Returns the first matching ELEMENT
const admin = users.find(u => u.admin);
// { id: 1, admin: true }
// .some(): Returns a BOOLEAN if AT LEAST ONE matches
const hasAdmin = users.some(u => u.admin); // true
// .every(): Returns a BOOLEAN if ALL match
const allAdmins = users.every(u => u.admin); // falseCommon Pitfalls
- .find() returns undefined if no element matches. Always handle this case to avoid 'Cannot read properties of undefined' errors.
Interview Tips
- Always use .some() instead of .filter().length > 0 to check if an item exists, because .some() stops at the first match.
Real-World Example
Checking user permissions before routing.
example
javascript
const userRoles = ['editor', 'viewer'];
const canPublish = userRoles.some(role => role === 'admin');
if (!canPublish) {
showAccessDeniedError();
}