JavaScript Interview Question #44
What is the difference between find() and filter()?
Objects, Arrays & Core Data Handling Junior Beginner
Quick Interview Answer
find returns the first element that satisfies the callback, or undefined when no element matches. filter returns a new array containing every matching element.
Detailed Explanation
find returns the first element that satisfies the callback, or undefined when no element matches. filter returns a new array containing every matching element.
Use find when at most one matching result is needed, such as locating a user by ID. Use filter when the application requires all records satisfying a condition.
Code Example
const users = [
{ id: 1, name: "Ali" },
{ id: 2, name: "Asif" },
{ id: 3, name: "Ahmed" }
];
const user = users.find(u => u.id === 2);
const namesWithA =
users.filter(u => u.name.startsWith("A"));
console.log(user);