Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript findIndex()

findIndex returns the position of the first item that matches a condition.

It is useful when you need to update or remove items by index.

Why We Need It

Many updates require the index of an item. findIndex gives you that quickly.

It stops early, so it is efficient for lookups.

Syntax

array.findIndex((value, index, array) => condition)

Basic Example

1. Find index

const users = [{ id: 1 }, { id: 2 }];
const idx = users.findIndex((u) => u.id === 2);

console.log(idx);

Returns 1 for the item with id 2.

Real World Example

2. Not found

const nums = [1, 2, 3];
const idx = nums.findIndex((n) => n > 10);

console.log(idx); // -1

-1 indicates no match.

Multiple Use Cases

Find the Index

findIndex returns the index of the first item that matches.

If nothing matches, it returns -1.

Use for Updates

Once you have the index, you can update or remove the item.

This is useful in state updates and list editing.

Stop Early

Like find, it stops after the first match.

That makes it efficient for lookups.

More Examples

3. Update by index

const items = [{ id: 1, done: false }];
const idx = items.findIndex((i) => i.id === 1);
if (idx !== -1) items[idx].done = true;

console.log(items);

Use the index to update a specific item.

4. Remove item

const list = ["a", "b", "c"];
const idx = list.findIndex((v) => v === "b");
if (idx !== -1) list.splice(idx, 1);

console.log(list);

Remove an item by index.

Comparison

Without

let idx = -1;
for (let i = 0; i < users.length; i++) {
  if (users[i].id === 2) {
    idx = i;
    break;
  }
}

With

const idx = users.findIndex((u) => u.id === 2);

Common Mistakes and Fixes

Forgetting -1 case

Always check if index is -1 before using it.

Expecting the value

findIndex returns the position, not the item.

Using findIndex for multiple matches

Use filter or a loop to collect all matches.

Interview Questions

What does findIndex return if no match?

-1.

When should you use findIndex?

When you need the position to update or remove.

Does findIndex stop after first match?

Yes, it stops early.

Practice Problem

Practice: Find the index of the first negative number.

const nums = [3, -1, 4];
// TODO: find index of first negative

One Possible Solution

const nums = [3, -1, 4];
const idx = nums.findIndex((n) => n < 0);
console.log(idx);

Frequently Asked Questions

What does findIndex return?

The index of the first match or -1.

When should I use find instead?

Use find when you need the element, not the index.

Does findIndex mutate the array?

No, it does not.

Try It Yourself

Try changing the array to see different indexes.