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.
Example 2: Find the first element greater than 20.
Example 3: Find the first element greater than 4.