How does find works in javscript?

How does "find" work in JavaScript?

If you are working with arrays in JavaScript, you may need to search for a particular element in the array. This is where the "find" method comes in handy.

The Syntax

The syntax for using "find" is:

array.find(function(currentValue, index, arr), thisValue)

The first parameter is a function that takes three arguments - currentValue, index, and arr. The second parameter is optional and refers to the value of "this" inside the function.

How it Works

The "find" method starts searching the array from the beginning and stops as soon as it finds an element that satisfies the condition specified in the function. The function returns true if the element meets the condition and false otherwise. Once the element is found, "find" returns the value of that element.

Example:

Let's say we have an array of numbers and we want to find the first number greater than 10. Here is how we would use "find":

const numbers = [5, 8, 12, 3, 19];
const foundNumber = numbers.find(function(number) {
  return number > 10;
});
console.log(foundNumber); // Output: 12

The function we passed to "find" takes one argument - "number" - which is the current element being processed. The function returns true if the current element is greater than 10 and false otherwise. In this case, the first element that satisfies the condition is 12 and that is what is returned.

Other Ways to Use "find"

There are other ways you can use "find" as well:

  • You can use arrow functions instead of regular functions:
const foundNumber = numbers.find(number => number > 10);
  • You can also use the "thisValue" parameter to set the value of "this" inside the function:
const person = {
  name: 'John',
  age: 30,
  hobbies: ['reading', 'running', 'swimming'],
  checkHobby: function(hobby) {
    return this.hobbies.find(h => h === hobby);
  }
};
console.log(person.checkHobby('running')); // Output: 'running'

In this example, we have an object "person" with a "checkHobby" method. The method takes one argument - "hobby" - and returns true if the person has that hobby and false otherwise. We are using "find" to search the "hobbies" array of the person object.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe