JavaScript findIndex in TypeScript
The JavaScript findIndex method answers one question: where is the first element that passes my test? It hands back a position, not the element, and it has been in the language since ES6.
The runtime behaviour takes one example. The half worth reading is everything around it: the -1
it returns when nothing matches, the bug that -1 causes in almost every codebase, and why a type
guard inside the predicate buys you nothing.
What JavaScript findIndex does
Run a predicate over the elements. Return the index of the first one that passes.
const taskQueue = ['sync', 'retry', 'cleanup']
const retryIndex = taskQueue.findIndex((task) => task === 'retry') // 1
const deployIndex = taskQueue.findIndex((task) => task === 'deploy') // -1Like some, it short-circuits. The moment the predicate returns something truthy, the remaining
elements are never visited. Unlike some, you get back a usable position instead of a boolean.
That -1 is the whole design. Arrays are zero-indexed, so there is no spare index to mean "nothing
here" — 0 is a real answer. The method borrows the sentinel indexOf has used since ES5.
The -1 sentinel is a trap
Here is the bug. findIndex returns a number, and developers reach for a truthiness check out of
habit. Both ends of the range betray you.
const inventoryItems = ['laptop', 'monitor', 'keyboard']
const laptopIndex = inventoryItems.findIndex((item) => item === 'laptop') // 0
const tabletIndex = inventoryItems.findIndex((item) => item === 'tablet') // -1
const laptopFoundWrong = Boolean(laptopIndex) // ❌ false — 0 is falsy, but the laptop is right there
const tabletFoundWrong = Boolean(tabletIndex) // ❌ true — -1 is truthy, and there is no tablet
const laptopFoundRight = laptopIndex !== -1 // ✅ true
const tabletFoundRight = tabletIndex !== -1 // ✅ falseBoth wrong answers come from the same place: 0 is falsy and every other number, negative ones
included, is truthy. If that rule is not already muscle memory, the
truthy and falsy page is worth five minutes.
TypeScript will not save you here. if (laptopIndex) is a perfectly valid check on a number —
the types are fine and the logic is broken. Compare against -1 explicitly, every time. Some
people prefer >= 0; it reads better and means the same thing.
findIndex vs indexOf
indexOf compares values with strict equality. findIndex runs a function. For primitives they
overlap, and indexOf is the shorter spelling.
const plainNumbers = [10, 20, 30]
const twentyByValue = plainNumbers.indexOf(20) // 1
const twentyByPredicate = plainNumbers.findIndex((value) => value === 20) // 1Objects are where they split. Strict equality on objects compares references, so indexOf can only
find an object you already hold.
type UserRecord = { id: number; role: string }
const userRecords: UserRecord[] = [
{ id: 1, role: 'editor' },
{ id: 2, role: 'admin' },
]
const adminByValue = userRecords.indexOf({ id: 2, role: 'admin' }) // ❌ -1, different object
const adminByPredicate = userRecords.findIndex((user) => user.role === 'admin') // ✅ 1The freshly written object literal is a different reference, so indexOf reports -1 even though
a structurally identical record sits at index 1. Any search by field is a findIndex job.
There is one more gap, and it catches people working with numbers. indexOf uses strict equality,
and NaN is not equal to itself.
const measurementValues = [1.5, NaN, 3.5]
const nanByValue = measurementValues.indexOf(NaN) // ❌ -1 — NaN !== NaN
const nanByPredicate = measurementValues.findIndex((value) => Number.isNaN(value)) // ✅ 1If an array can hold NaN, indexOf cannot locate it. findIndex with Number.isNaN can.
findIndex vs find
Same predicate, different return value. find gives you the element, findIndex gives you its
position.
type PendingOrder = { id: string; total: number }
const orderList: PendingOrder[] = [
{ id: 'a-1', total: 40 },
{ id: 'b-2', total: 120 },
]
const bigOrder = orderList.find((order) => order.total > 100) // PendingOrder | undefined
const bigOrderIndex = orderList.findIndex((order) => order.total > 100) // numberThe "not found" values differ in a way that matters. find returns undefined, which TypeScript
puts in the type — you are forced to handle it, and
optional handling gets you a narrowed element for free.
findIndex returns -1, which is just a number. The type system sees nothing unusual, so the
check is on you.
Reach for find when you want the data. Reach for findIndex when you need the position — to
mutate the array, to splice, or to pair it with a second array.
The predicate's typed parameters
The callback receives three arguments, and TypeScript infers all of them from the array.
const sampleWords = ['alpha', 'beta', 'gamma']
const wordIndex = sampleWords.findIndex((word, position, wholeArray) => {
// word: string
// position: number
// wholeArray: string[]
return word.length > 4 && position < wholeArray.length
})No annotations needed. The element type flows from sampleWords, which is why declaring your array
properly pays off — see array types for what TypeScript infers from a
literal.
The declaration in the standard library looks like this:
interface FindIndexSignature<T> {
findIndex(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: unknown): number
}Two details are easy to miss. The predicate returns unknown, not boolean — any truthy value
counts, so (user) => user.name compiles and works. And the return type is plain number. There is
no literal union, no branded type, nothing that marks -1 as special. More on why that matters in
function types.
A type guard in the predicate narrows nothing
This is the mistake worth correcting. Writing a type predicate inside findIndex looks like it
should narrow the result. It does not.
type ShapeCircle = { kind: 'circle'; radius: number }
type ShapeSquare = { kind: 'square'; side: number }
type MixedShape = ShapeCircle | ShapeSquare
const shapeCollection: MixedShape[] = [
{ kind: 'square', side: 4 },
{ kind: 'circle', radius: 2 },
]
const circleIndex = shapeCollection.findIndex((shape): shape is ShapeCircle => shape.kind === 'circle')
const shapeAtIndex = shapeCollection[circleIndex] // MixedShape — still the full unionThe guard is allowed, because a type predicate function is assignable to a predicate returning
unknown. It just has nowhere to apply. findIndex returns a number, and a number carries no
information about what lives at that position. Indexing back into the array gives you the declared
element type, union and all.
javascript findIndex shares this limitation with some, which
never narrows either. Narrow after you index:
if (circleIndex !== -1) {
const candidateShape = shapeCollection[circleIndex]
if (candidateShape.kind === 'circle') {
const circleArea = Math.PI * candidateShape.radius ** 2
}
}Verbose, but honest. If you only want the element, find with a type guard does narrow — another
reason to pick the right method for the job.
findLastIndex searches backwards
ES2023 added the mirror image. Same predicate, same -1, opposite direction.
const eventLog = [
{ level: 'info', message: 'started' },
{ level: 'error', message: 'disk full' },
{ level: 'info', message: 'retrying' },
{ level: 'error', message: 'gave up' },
]
const firstErrorIndex = eventLog.findIndex((entry) => entry.level === 'error') // 1
const lastErrorIndex = eventLog.findLastIndex((entry) => entry.level === 'error') // 3It needs a lib that includes ES2023. If your tsconfig.json pins "lib": ["es2020", "dom"], the
method exists at runtime in current engines but TypeScript will not admit it. Bump to "es2023" or
"esnext". The tsconfig page covers the setting.
Holes and readonly arrays
findIndex visits every index from 0 to length - 1, including holes in a sparse array. That
sets it apart from forEach, filter, map and some, which all skip holes.
const sparseScores = [10, , 30]
const sparseVisits: number[] = []
sparseScores.findIndex((score, position) => {
sparseVisits.push(position)
return false
})
// sparseVisits is [0, 1, 2] — the hole at index 1 was visitedThe hole arrives in the predicate as undefined, while TypeScript still types the parameter as
number. Sparse arrays are rare and worth avoiding, but if one reaches your predicate, this is why
the types and the runtime disagree.
Readonly arrays and tuples work normally — findIndex only reads, so nothing is lost.
const readonlyFlags = ['draft', 'review', 'published'] as const
const reviewIndex = readonlyFlags.findIndex((flag) => flag === 'review') // 1With as const the predicate parameter narrows to the literal union
'draft' | 'review' | 'published', so a typo in the comparison is a compile error instead of a
permanent -1. That is a real argument for declaring fixed lists this way.
A typed helper worth writing
The sentinel is easy to forget, and TypeScript cannot remind you. If you do this often, wrap it once and let a discriminated union carry the result.
type LocateResult<T> = { found: true; index: number; value: T } | { found: false }
function locateIndex<T>(items: readonly T[], predicate: (item: T) => boolean): LocateResult<T> {
const position = items.findIndex(predicate)
if (position === -1) {
return { found: false }
}
return { found: true, index: position, value: items[position] }
}
const catalogueEntries = [{ code: 'x1' }, { code: 'x2' }]
const locatedEntry = locateIndex(catalogueEntries, (entry) => entry.code === 'x2')
if (locatedEntry.found) {
const resolvedIndex = locatedEntry.index // number
const resolvedValue = locatedEntry.value // { code: string }
}Now the index is unreachable until you have checked found, and you get the element in the same
step. The -1 lives in exactly one function instead of every call site.
Why you wanted the index in the first place
Mutation. This is the case find cannot cover, and the reason findIndex stays in rotation.
type CartLine = { sku: string; quantity: number }
const shoppingCart: CartLine[] = [
{ sku: 'TS-101', quantity: 1 },
{ sku: 'TS-204', quantity: 3 },
]
const lineIndex = shoppingCart.findIndex((line) => line.sku === 'TS-204')
if (lineIndex !== -1) {
// replace in place
shoppingCart[lineIndex] = { ...shoppingCart[lineIndex], quantity: 10 }
}Removing works the same way, with splice taking the index directly:
const removalIndex = shoppingCart.findIndex((line) => line.sku === 'TS-101')
if (removalIndex !== -1) {
shoppingCart.splice(removalIndex, 1)
}Both guards are mandatory. Skip the !== -1 check and splice(-1, 1) quietly deletes the last
element — a correct-looking call that removes the wrong row. That single missing comparison is the
most expensive version of this bug.
If you would rather not mutate, map with an index comparison or filter gives you a new array and
sidesteps the sentinel entirely. flatMap covers the same ground when each
element maps to zero or more results.
The other everyday use is lining up two arrays that share positions — a pattern that shows up with form fields, table columns and anything parsed out of a CSV.
const seatNumbers = ['1A', '1B', '1C']
const seatHolders = ['Ada', 'Grace', 'Alan']
const seatIndex = seatNumbers.findIndex((seat) => seat === '1B')
const seatHolder = seatIndex === -1 ? 'unassigned' : seatHolders[seatIndex] // 'Grace'Parallel arrays are fragile by nature, but when you are handed them this is the clean way across.
Do not search twice
One anti-pattern is common enough to call out. Having found the element, people search again to get its position.
const temperatureReadings = [11, 24, 31]
const hotReading = temperatureReadings.find((reading) => reading > 20)
const hotReadingIndex = temperatureReadings.indexOf(hotReading as number) // ❌ two passes, and a castTwo walks of the array, plus a cast to silence the undefined that find correctly returned. Ask
for the index once and read the element from it.
const warmIndex = temperatureReadings.findIndex((reading) => reading > 20)
if (warmIndex !== -1) {
const warmReading = temperatureReadings[warmIndex] // ✅ one pass, no cast
}Any time a cast appears next to an array search, the method choice is usually the thing to fix.
Summary
findIndex runs a predicate and returns the position of the first match, or -1.
- Always compare with
!== -1or>= 0. Never test the index for truthiness —0is falsy and-1is truthy, so both ends of the range lie to you. - Use
indexOffor primitives you can compare by value,findIndexfor anything matched by field. - Use
findwhen you want the element,findIndexwhen you want the position — usually to mutate. - A type guard inside the predicate compiles but narrows nothing. Narrow after indexing.
findLastIndexsearches from the end and needslibat ES2023 or later.
TypeScript types the callback for you and then steps aside. The -1 contract is a runtime
convention the type system cannot enforce, which makes it the one part you have to remember.
Become a TypeScript Pro
Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.
Or start solving right away: explore all TypeScript challenges