Khachatryan-dev

JavaScript's find() method

Details, examples, practice

Aram
Khachatryan

JavaScript's find() Method


When you need to find the first value in an array that satisfies a certain condition, the best choice is the find() method.


It returns the first element that satisfies your defined callback function. If nothing matches, it returns undefined.




Syntax


    array.find(function(element, index, array) {
      // returns true/false
    });

Parameters


  • element – the current element
  • index – the current index
  • array – the entire array



Simple Example


    const users = [
      { id: 1, name: 'Anna' },
      { id: 2, name: 'David' },
      { id: 3, name: 'Levon' }
    ];
    
    const foundUser = users.find(user => user.id === 2);
    
    console.log(foundUser); // { id: 2, name: 'David' }

Returns the first user whose id is equal to 2.




If Nothing Is Found, It Returns undefined


Example


    const result = users.find(user => user.id === 5);
    console.log(result); // undefined



Comparison with filter()


  • filter() always returns an array
  • find() returns only the first matching element or undefined

    const even = [1, 2, 3, 4, 5].find(n => n % 2 === 0);  // 2
    const evenList = [1, 2, 3, 4, 5].filter(n => n % 2 === 0); // [2, 4]

How the find() Method Works Internally


When we call:


    [1, 2, 3].find(fn);

This is the same as:


    Array.prototype.find.call([1, 2, 3], fn);



Let's Write Our Own myFind() Function from Scratch


    function myFind(array, callback) {
      for (let i = 0; i < array.length; i++) {
        if (callback(array[i], i, array)) {
          return array[i];
        }
      }
      return undefined;
    }

Usage example:


    const items = [10, 20, 30, 40];

    const found = myFind(items, function(item) {
      return item > 25;
    });
    
    console.log(found); // 30



Attach It as a Method to Array


    Array.prototype.myFind = function(callback) {
      for (let i = 0; i < this.length; i++) {
        if (callback(this[i], i, this)) {
          return this[i];
        }
      }
      return undefined;
    };

We use it like this:


    const numbers = [5, 10, 15, 20];

    const found = numbers.myFind(n => n > 10);
    console.log(found); // 15



Conclusion


  • find() searches for the first value that satisfies a certain condition.
  • If nothing is found, it returns undefined.
  • It's useful when you need to find a single item.
  • You can write your own version using a simple for loop.
5.00 / 1
Buy me a coffee
  • 0
  • 14

Discover More Content

Comments
No data
No comments yet. Be the first to comment!
Leave a Comment
You must be logged in to leave a comment.Login