Skip to content

JavaScript – find And findIndex

Last updated on January 30, 2021

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
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments