JavaScript(JS) array method - find
The find()
method is an array method in JavaScript that returns the value of the first element in the array that satisfies a specified testing function. If no such element is found, undefined
is returned.
Here's the syntax of the find()
method:
array.find(callback, thisArg);
array
is the array that thefind()
method is called on.callback
is a function that takes three arguments: the current value of the element being processed, the index of the element being processed, and the array that thefind()
method was called on. This function should return a boolean value indicating whether the element satisfies the test or not.thisArg
is an optional argument that specifies the value ofthis
inside thecallback
function.
The find()
method iterates through the array and calls the callback
function on each element. If the callback
function returns true
for an element, the find()
method returns the value of that element and stops iterating. If no element satisfies the test, the find()
method returns undefined
.
Here's an example of how to use the find()
method:
let array = [1, 2, 3, 4, 5]; let foundElement = array.find(function(element) { return element > 2; }); console.log(foundElement); // 3
In this example, we have an array array
containing the elements [1, 2, 3, 4, 5]
. We use the find()
method to find the first element that is greater than 2. The callback
function checks whether the current element is greater than 2 and returns a boolean value. The find()
method iterates through the array and returns the value of the first element that satisfies the test. The console.log()
statement outputs the value of foundElement
, which is 3
.
Note that the find()
method returns only the value of the first element that satisfies the test. If you need to find all the elements that satisfy the test, you can use the filter()
method. Also, the find()
method was introduced in ECMAScript 6, so it may not be supported by older browsers.