The find() method in JavaScript looks through an array and returns the first item that meets a specific condition you provide. If no item matches, it returns undefined. It skips any empty space in the array and doesn’t alter the original array.
Syntax:
array.find(function(currentValue, index, arr), thisArg)Parameters:
- function(currentValue, index, arr): A function to execute on each value in the array until the first element satisfying the condition is found. It takes three parameters:
- currentValue: The current element being processed in the array.
- index (optional): The index of the current element being processed in the array.
- arr (optional): The array find() was called upon.
- thisValue (optional): A value to use as this when executing the callback function.
Return value:
- It returns the array element value if any of the elements in the array satisfy the condition, otherwise, it returns undefined.
Different Examples of find() Method
Example 1: Find the first positive number in the array.
// Input array contain some elements.
let array = [-10, -0.20, 0.30, -40, -50];
// Method (return element > 0).
let found = array.find(function (element) {
return element > 0;
});
// Printing desired values.
console.log(found);
Example 2: Find the first element greater than 20.
// Input array contain some elements.
let array = [10, 20, 30, 40, 50];
// Method (return element > 20).
let found = array.find(function (element) {
return element > 20;
});
// Printing desired values.
console.log(found);
Example 3: Find the first element greater than 4.
// Input array contain some elements.
let array = [2, 7, 8, 9];
// Provided testing method (return element > 4).
let found = array.find(function (element) {
return element > 4;
});
// Printing desired values.
console.log(found);