Categories
JavaScript

JavaScript find method

The JavaScript find method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned, as per MDN.

This basically means that we need to provide some criteria, in form of, callback, function. Then, an array is iterated and the callback function is called once for each index in the array. Once the first element is found, the .find() method returns that element. If no element is found .find() method returns undefined.

Let’s take a look at the example below. We want to return the first element of an array that is greater than 10.

const arr = [1, 5, 7, 12, 22, 25];

let val = arr.find(el => el > 10);

console.log(val);

//Result 12

As we can see, the first number .find() returned is 12. That is the result we have expected.

Another, more practical example would be to find products in an array of objects.

const prod = [
    {
        id: 1, 
        name: "Laptop"
    }, 
    
    {
        id: 2,
        name: "Smartphone"
    }, 
    {
        id: 3, 
        name: "TV"
    }
];

function isProduct(product) {
  return product.name === 'Smartphone';
}

console.log(prod.find(isProduct));

//Result: 
// {id: 2, name: 'Smartphone'}

The same functionality, as in the above example, can be achieved by using Object destructuring, inside JavaScript find method.

const prod = [
    {
        id: 1, 
        name: "Laptop"
    }, 
    
    {
        id: 2,
        name: "Smartphone"
    }, 
    {
        id: 3, 
        name: "TV"
    }
];

function isProduct(product) {
  return product.name === 'Smartphone';
}

console.log(prod.find( ({ name }) => name === 'Smartphone' ));

//Result: 
// {id: 2, name: 'Smartphone'}

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like Validate files in JavaScript easily using these 2 methods.