JavaScript Interview Question #45

What is the difference between findIndex() and indexOf()?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

indexOf searches for a specific value using strict equality and returns its index, or -1 when not found. findIndex accepts a callback and returns the index of the first element satisfying the condition.

Detailed Explanation

indexOf searches for a specific value using strict equality and returns its index, or -1 when not found. findIndex accepts a callback and returns the index of the first element satisfying the condition.

indexOf works well for primitive values or an exact object reference. findIndex is more suitable when searching objects by a property or applying custom logic.

Code Example

const numbers = [10, 20, 30];
console.log(numbers.indexOf(20)); // 1

const users = [
    { id: 10, name: "Ali" },
    { id: 20, name: "Asif" }
];

const index =
    users.findIndex(u => u.id === 20);

console.log(index); // 1