JavaScript ES6 – What are the difference between array indexOf and findIndex methods?

The main difference between JavaScript indexOf() and findIndex() methods are functions parameters. indexOf() expects a value as first parameter while findIndex() expects a callback as first parameter.

Let’s see how these methods are different from each other:

JavaScript indexOf() method

The indexOf() method expects a value as first parameter. This makes it a good choice to find the index in arrays of primitive types (like string, number, or boolean).

  • expects value as parameter
  • returns index if match found
  • returns -1 if no match found
const arr = [23, 12, 15, 20];
const index = arr.indexOf(15);
console.log(index);

// OUTPUT
// 2

JavaScript findIndex() method

The findIndex() method expects a callback as first parameter. Use this if you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.

  • expects callback as parameter
  • use for more complex conditions & objects
  • returns index if match found
  • returns -1 if no match found
const products = [
  { type: "apple", quantity: 9 },
  { type: "banana", quantity: 2 },
  { type: "orange", quantity: 8 }
];

const appleIndex = products.findIndex((product) => product.type === 'banana');
console.log(appleIndex);

// OUTPUT
// 1
%d bloggers like this: