find() in an array
The find() method is one of the most commonly used methods in JavaScript for finding a specific element in an array by a condition.
It does not filter or iterate the whole array to build a new one - it finds the first matching element and stops.
Syntax
const result = array.find((element, index, array) => {
return condition;
});Callback parameters:
| Argument | Description |
|---|---|
element | The current array element |
index | The index of the current element |
array | The original array itself |
Example 1. Finding a number in an array
const numbers = [1, 5, 10, 15, 20];
const found = numbers.find(num => num > 10);
console.log(found); // 15
find()returned the first value satisfying the condition (> 10) and stopped searching. If nothing is found, it returnsundefined.
Example 2. Finding an object by property
const users = [
{ id: 1, name: 'Tim', age: 25 },
{ id: 2, name: 'Alex', age: 17 },
{ id: 3, name: 'John', age: 30 }
];
const user = users.find(u => u.id === 3);
console.log(user);
// { id: 3, name: 'John', age: 30 }A very common case - finding an element in an array of objects (for example, by
id).
Example 3. When the element is not found
const arr = [10, 20, 30];
const res = arr.find(num => num > 50);
console.log(res); // undefinedIf no matching element is found,
undefinedis returned, not an error.
Frequent mistakes
- Expecting an array instead of a single element:
const result = arr.find(num => num > 5);
console.log(result.length); // Error - find returns an element, not an arrayIf you need all matching elements, not just one, use filter().
- Forgotten
returnin curly braces:
arr.find(num => { num > 5 }); // always undefinedCorrect:
arr.find(num => num > 5);
// or
arr.find(num => { return num > 5 });When to use find()
| Goal | Does find() fit |
|---|---|
| Find the first element satisfying the condition | Yes |
| Find all matching elements | No - use filter() |
| Check whether at least one element exists | No - use some() |
| Transform the data | No - use map() |
In short:
find()returns the first element that satisfies the condition, orundefinedif there is none.
Formula to remember:
arr.find(condition) -> one_element_or_undefined
Comparison with similar methods
| Method | What it returns | When it stops | Example |
|---|---|---|---|
| find() | The first matching element | After the first match | [1,2,3].find(x => x>1) -> 2 |
| filter() | All matching elements (an array) | After going through the whole array | [1,2,3].filter(x => x>1) -> [2,3] |
| findIndex() | Index of the found element | After the first match | [10,20,30].findIndex(x=>x>10) -> 1 |
| some() | true/false (whether at least one was found) | After the first match | [1,2,3].some(x=>x>2) -> true |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.