The find() method in JavaScript is used to return the value of the first element in an array that satisfies the provided testing function. It does not modify the original array.
Syntax
array.find(callback(element, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback | A function to test each element of the array. It takes three arguments: element, index, and array. |
element | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array find() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Any | The value of the first element that satisfies |
the provided testing function. |
Example 1: Finding an Even Number
This code demonstrates how to use the find() method to find the first even number in an array.
let Arr = [1, 3, 5, 7, 8, 9]; let evenNumber = Arr.find(function(element) { return element % 2 === 0; }); console.log(evenNumber);
Output:
8
Example 2: Using Arrow Function
This code uses an arrow function to achieve the same result as the previous example.
let numbers = [1, 3, 5, 7, 8, 9]; let evenNumber = numbers.find(element => element % 2 === 0); console.log(evenNumber);
Output:
8
Example 3: Finding an Object in an Array
This code demonstrates how to use the find() method to find an object in an array based on a specific property value.
let products = [ { id: 1, name: "Product 1" }, { id: 2, name: "Product 2" }, { id: 3, name: "Product 3" } ]; let product = products.find(element => element.id === 2); console.log(product);
Output:
{ id: 2, name: "Product 2" }
Example 4: Using a Provided thisArg
This code demonstrates how to use the find() method with a provided thisArg to access a variable outside the callback function.
let fruits = ["apple", "banana", "cherry"]; let findByLength = function(element) { return element.length === this.length; }; let fruit = fruits.find(findByLength, { length: 6 }); console.log(fruit);
Output:
"banana"
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
45 | 12 | 25 | 32 | 8 |