javascript find method

JavaScript Find Method

The find() method in JavaScript is used to search for a particular element in an array and returns the first element that satisfies the condition specified in the function. If no element satisfies the condition, then it returns undefined.

Syntax:

array.find(function(currentValue, index, arr), thisValue)
  • function(currentValue, index, arr) - Required. A function to be executed for every element in the array.
  • thisValue - Optional. A value to be passed to the function to be used as its "this" value.

Let's consider an example to understand the find() method:


const numbers = [10, 20, 30, 40, 50];

const result = numbers.find(function(number) {
  return number > 25;
});

console.log(result); // Output: 30

In the above example, we have an array of numbers. We want to find the first number in the array which is greater than 25. So, we pass a function to the find() method which returns true if the number is greater than 25. The find() method returns the first number that satisfies this condition, which is 30 in our case.

We can also use arrow functions instead of a regular function:


const numbers = [10, 20, 30, 40, 50];

const result = numbers.find(number => number > 25);

console.log(result); // Output: 30

The find() method can also take a second parameter which is used as the value of this inside the function:


const person = {
  name: 'John',
  age: 30,
  hobbies: ['reading', 'swimming', 'travelling'],
  findHobby(hobby) {
    return this.hobbies.find(element => element === hobby);
  }
}

console.log(person.findHobby('swimming')); // Output: swimming

In the above example, we have an object person with a property hobbies which is an array. We want to find if the person has a particular hobby or not. So, we define a method findHobby() which takes a parameter hobby and uses the find() method to search for the hobby in the hobbies array. We use the this keyword inside the function to access the hobbies array of the person object.

In conclusion, the find() method is a very useful method in JavaScript which can be used to search for elements in an array based on a condition. It is easy to use and can save a lot of time and effort.

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