Posted by Arjun Arjun on Monday 27th July 2020, 1 minute read

JavaScript - find And findIndex

JavaScript Functions

The Array.prototype.findIndex() and Array.prototype.find() methods are useful to search the provided array.

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

const ages = [20, 30, 40, 50, 60];

console.log(ages.findIndex(age => age >= 20)) 
// expected output: 0

console.log(ages.findIndex(age => age === 40)) 
// expected output: 2

console.log(ages.findIndex(age => age >= 100)) 
// expected output: -1

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

const ages = [20, 30, 40, 50, 60];

console.log(ages.find(age => age >= 20)) 
// expected output: 20

console.log(ages.find(age => age === 40)) 
// expected output: 40

console.log(ages.find(age => age >= 100)) 
// expected output: undefined
...
Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.