Array.find()
The Array.find()
method in JavaScript is used to retrieve the first element in an array that satisfies a provided testing function. If no elements satisfy the testing function, undefined
is returned.
Syntax
find(callbackFn)
find(callbackFn, thisArg)
Parameters
Parameter | Description |
---|---|
callbackFn | A function to execute on each element in the array. It should return true to indicate a match, or false otherwise. It accepts three arguments:
|
thisArg | Optional. An object to use as this when executing the callback function. |
Return Value
The find()
method returns the first element in the array that satisfies the testing function. If no elements satisfy the condition, it returns undefined
.
Examples
1. Finding an Element in an Array
This example demonstrates how to find the first element in an array that satisfies a condition.
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(element => element > 10);
console.log(found);
Output
12
The first element greater than 10 is 12
.
2. Using thisArg
with find()
You can use the thisArg
parameter to specify the value of this
inside the callback function.
const inventory = [
{ name: "apple", quantity: 10 },
{ name: "banana", quantity: 0 },
{ name: "cherry", quantity: 25 }
];
function isAvailable(fruit) {
return fruit.quantity > 0;
}
const foundFruit = inventory.find(isAvailable, inventory);
console.log(foundFruit);
Output
{ name: "apple", quantity: 10 }
The apple
object is the first item in the inventory with a quantity greater than 0.
3. Finding undefined
When No Match is Found
If no elements satisfy the testing function, the find()
method returns undefined
.
const numbers = [5, 12, 8, 130, 44];
const result = numbers.find(element => element > 200);
console.log(result);
Output
undefined
Since no element is greater than 200, undefined
is returned.
4. Using find()
to Search Objects in an Array
The find()
method is useful for finding specific objects in an array based on a condition.
const users = [
{ id: 1, name: "Akash" },
{ id: 2, name: "Bhairav" },
{ id: 3, name: "Chandra" }
];
const user = users.find(user => user.id === 2);
console.log(user);
Output
{ id: 2, name: "Bhairav" }
The object with id
equal to 2 is returned.