The JavaScript array find() method returns the first element of the given array that satisfies the provided function condition.
The find()
method executes a function for each array element.
The find()
method retuns undefined
if no elements are found.
The find()
method does not execute the function for empty elements.
The find()
method does not change the original array.
In this tutorial, you will learn about the JavaScript Array find() method with the help of examples.
Syntax
array.find(callbackFunction(currentValue, index, arr),thisValue)
- callbackFunction– A function to run for each array element. It represents the function that test the condition.
- currentValue– The current element of array.
- index – It is optional. The index of current element.
- arr – It is optional. The array on which find() operated.
- thisArg – It is optional. The value to use as this while executing callback. Default
undefined
.
Return Value
The value of first element of the array that satisfies the function condition. Returns undefined if none of the elements satisfy the function.
Examples
The following example finds an element in the array that is a prime number (or returns undefined if there is no prime number):
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
let numbers = [1, 3, 4, 9, 8];
// function to check even number
function isEven(element) {
return element % 2 == 0;
}
// get the first even number
let evenNumber = numbers.find(isEven);
console.log(evenNumber);
// Output: 4