The find()
method is used to search through an array and return the first element that meets a specified condition. It executes a provided function once for each array element, until it finds a match, or finishes checking all elements.
Syntax
arr.find(callback(element, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback (Required) | A function that is executed for each element in the array. |
element | The current element being processed in the array. |
index (Optional) | The current element is being processed in the array. |
array (Optional) | The array that find() was called on. |
thisArg (Optional) | A value to use as this when executing the callback function. If not provided, this defaults to the global object (in non-strict mode) or undefined (in strict mode). |
Return Value
The find()
method returns the first element in the array that satisfies the condition provided in the callback function. If no elements match, it returns undefined
.
Example 1: Finding a Specific Element in an Array
let numbers = [1, 3, 5, 7, 9]; // Finding the first number greater than 4 let found = numbers.find(num => num > 4); console.log(found); // Output: 5
Example 2: Using the find()
Method with Objects
If you have an array of objects, you can use the find()
method to find an object that satisfies a specific condition.
let users = [ { id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' } ]; // Finding the user with id 2 let user = users.find(user => user.id === 2); console.log(user); // Output: { id: 2, name: 'Alice' }
In this case, find()
returns the first object with id
equal to 2
.
Example 3: When No Element Matches the Condition
let numbers = [2, 4, 6, 8, 10]; // Finding the first odd number let found = numbers.find(num => num % 2 !== 0); console.log(found); // Output: undefined
Since no odd number is present in the array, find()
returns undefined
.
Example 4: Using Index and Array in the Callback
let fruits = ['apple', 'banana', 'cherry']; // Find the first fruit that starts with the letter 'b' let result = fruits.find((fruit, index, array) => fruit[0] === 'b'); console.log(result); // Output: banana
Here, find()
checks each element for the condition fruit[0] === 'b'
, and it returns 'banana'
because it’s the first fruit starting with the letter ‘b’.
Example 5: Using thisArg
to Bind the Context
let numbers = [1, 2, 3, 4, 5]; let context = { factor: 2 }; // Use 'thisArg' to set the context for 'this' inside the callback let result = numbers.find(function(num) { return num > this.factor; }, context); console.log(result); // Output: 3
Supported Browsers
- Chrome: 49+
- Firefox: 25+
- Safari: 9+
- Edge: 12+
- Opera: 36+
- Internet Explorer: Not supported (requires polyfill)
Note: The find() method was introduced in ECMAScript 6 (ES6), so it is supported in modern browsers. However, if you need to support older browsers (like Internet Explorer), you may need to polyfill the find() method.