Jan 30, 2022

How to find an element in an array in Javascript?

If you know how to find an element from an array in other languages like python or java, you may think of using the same method to find an element in the array. But there is an easy and default way to find an element in an array in Javascript.

By

Muthukumar

Array.prototype.find()

The find method returns the first element that satisfies the condition that is checked by the callback function.

The callback function is called with three parameters. The first parameter is the current element, the second parameter is the current index and the last parameter is the array itself it is called with.

Example:

function findNegativeNumber(currentElement) {
  return currentElement < 0 // The first element to satisfies this condition will be returned by the find method.
}

const numbers = [40, 30, -19, 10, -2, 9]

const firstNegativeNumber = numbers.find(findNegativeNumber)

console.log(firstNegativeNumber) // -19

Continue Reading