The find()
method in JavaScript is used to search through an array and return the first element that satisfies a provided testing function. If no element meets the condition, it returns undefined
.
Syntax:
array.find(callback(element[, index[, array]])[, thisArg])
- callback: A function that is called for each element in the array. It takes three arguments:
element
: The current element being processed.index
(optional): The index of the current element.array
(optional): The array thatfind()
was called on.
- thisArg (optional): A value to use as
this
when executing the callback function.
How it works:
- The
find()
method iterates over the array, and for each element, it invokes the callback function. - If the callback function returns
true
for an element, that element is returned and the iteration stops. - If the callback function never returns
true
for any element,undefined
is returned.
Example:
let numbers = [5, 12, 8, 130, 44];
let found = numbers.find(element => element > 10);
console.log(found); // Output: 12
In this example:
- The
find()
method is searching for the first number greater than10
. - It checks each element one by one. When it reaches
12
, it satisfies the condition (12 > 10
), so12
is returned.
Notes:
- The method only returns the first element that matches the condition. It does not continue searching once a match is found.
- If no element satisfies the condition, it returns
undefined
.
let noMatch = numbers.find(element => element > 200);
console.log(noMatch); // Output: undefined