JavaScript find(), findIndex() and Last-Match Search
Quick answer
Find-family methods stop at the first qualifying index in their chosen traversal direction. Choose value-returning or index-returning forms based on what the caller needs.
How it works
find and findIndex traverse forward; findLast and findLastIndex traverse backward. The callback receives value, index, source. Ordinary holes are read as undefined and visited. Missing match returns undefined for value methods and -1 for index methods. A matched undefined is indistinguishable from no match by value alone.
const a = [5, 12, 8, 20];console.log(a.find(n => n > 10), a.findIndex(n => n > 10));Expected output in Node.js:
12 1The first match is at index 1.
const a = [2, 7, 9, 4];console.log(a.findLast(n => n > 5), a.findLastIndex(n => n > 5));Expected output in Node.js:
9 2Backward traversal reaches 9 first.
Common mistakes
An index of zero is a successful match. Compare with -1 instead of treating the index as a Boolean.
Practice
Find the first and last passing score, and test a list with no passing score.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript find(), findIndex() and Last-Match Search — Knowledge Check
Apply the taught concept and predict the output.
Which method distinguishes a found undefined from no match using its result alone?
What is findLastIndex return value when no element qualifies?
What value is normally supplied for an ordinary hole by find?
What is the exact console output in JavaScript find(), findIndex() and Last-Match Search example 1?
const a = [5, 12, 8, 20];console.log(a.find(n => n > 10), a.findIndex(n => n > 10));What is the exact console output in JavaScript find(), findIndex() and Last-Match Search example 2?
const a = [2, 7, 9, 4];console.log(a.findLast(n => n > 5), a.findLastIndex(n => n > 5));