Problem Statement
What does the find method return?
Explanation
The find method returns the first element that satisfies the test function.
It stops searching as soon as it finds a match, making it efficient.
If no element matches, it returns undefined.
Find is useful when you need to retrieve a single item from an array based on a condition.
If you need the index instead of the element, use findIndex.
Code Solution
SolutionRead Only
const numbers = [5, 12, 8, 130, 44];
// Find first element greater than 10
const found = numbers.find(num => num > 10);
console.log(found); // 12 (stops at first match)
// Find in array of objects
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: 'Jane' }
// Returns undefined if not found
const notFound = numbers.find(num => num > 200);
console.log(notFound); // undefined
// Compare with filter (returns array)
const filtered = numbers.filter(num => num > 10);
console.log(filtered); // [12, 130, 44]
// findIndex returns index
const index = numbers.findIndex(num => num > 10);
console.log(index); // 1
// Practical use
const cart = [{id: 1, qty: 2}, {id: 2, qty: 1}];
const item = cart.find(item => item.id === 1);
if (item) {
item.qty++;
}