const - JS | lectureWorking With Arrays

The find Method

Working With Arrays

After the map, filter and reduce methods, we still have some methods to learn, which are also super important and used all the time. So in this lecture, we will talk about the find method.

As the name says, we can use the find method to retrieve one element of an array based on a condition. Let's consider again our movements array.

const movements = [300, 600, -800, 7000, -750, -150, 90, 1500];

Like the other array methods we've been talking about, the find method also accepts a callback function which will then be called as the method loops over the array.

movements.find((/* Params */)  => /* Condition */);

// OR

movements.find((/* Params */) => {
  return /* Condition */;

As always, the first parameter of the callback function is the current element of the array, and the returned value of the callback function is a boolean value which determines whether the current element is the one we are looking for.

movements.find((movement) => movement < 0);

Unlike the filter method, the find method will not return a new array but only the first element in the array that satisfies the provided condition. In other words, the first element in the array for which the operation movement < 0 becomes true. This represent the first withdrawal in the movements array.

const firstWithdrawal = movements.find((movement) => movement < 0);
console.log(firstWithdrawal); // -800

As you can see, the find method is a bit similar to the filter method, but there are two fundamental differences. First, the filter method returns all the elements in the array that satisfy the condition, whereas the find method will return the first element in the array that satisfies the condition. Secondly, and even more important, the filter method returns a new array, whereas the find method only returns the element itself and not an array.

⚠️ undefined is returned when no element in the array satisfies the condition.