Javascript Array - find() Method

Tutorialsrack 25/09/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.find().  How does this method work in javascript? 


This Array.prototype.find() method returns the first element from the provided array which passes the test that is implemented by the callback() function. If no elements pass the test, it returns undefined. This method is very similar to the filter() method. 

array.find(callback(element [, index [, array]]) [,thisParameter]);

This Method takes two parameters as given below:

  • callback: This parameter holds the function to be called for each element of the array. This function takes the mentioned parameters as below:
    • element: This parameter holds the current element of the array.
    • Index(Optional): This parameter holds the index of the current element within the array.
    • array(Optional): This parameter holds the reference to the original array.
  • thisParameter(Optional): This parameter holds the context to be passed as this is to be used while executing the callback function.

The find() method does not execute the callback function for empty elements. And it does not change the original array.

Here are some examples of Array.prototype.find() method:

//find the element in an array that is greater than 10
console.log([12, 5, 8, 130, 44].find(x => x > 10));
// output => 12

let cities = [
    {name: 'Los Angeles', population: 3792621},
    {name: 'New York', population: 8175133},
    {name: 'Chicago', population: 2695598},
    {name: 'Houston', population: 2099451},
    {name: 'Philadelphia', population: 1526006}

//find the city where the population is greater than 3000000
let metroCities = cities.find(city => city.population > 3000000);
//output=> { name: 'Los Angeles', population: 3792621 }

I hope this article will help you to understand the javascript Array built-in method Array.prototype.find()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

Related Posts


Recent Posts