Skip to content

JavaScript findIndex vs indexOf function | difference

  • by

The difference between the indexOf() and findIndex() function of JavaScript is:

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

arr.indexOf(element[, index])

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

array.findIndex(fun(curValue, index, arr), thisValue)

JavaScript findIndex vs indexOf

A simple example code finds the index in an array of objects, with the key of “Orange”. And find the index in a simple array“.

<!DOCTYPE html>
<html>
<body>

  <script>
    let fruits = [
    { type: "Apple", quantity: 90 },
    { type: "Banana", quantity: 20},
    { type: "Orange", quantity: 80},
    { type: "Pear", quantity: 100}
    ];

    let myIndex = fruits.findIndex(fruit => fruit.type === "Orange");
    console.log(myIndex);

    let arr = [ "Apple", "Banana", "Pear", "Orange"];
    let index = arr.indexOf("Orange")
    console.log(index)

  </script>
</body>
</html>

Output:

JavaScript findIndex vs indexOf function difference

When should use findIndex() vs indexOf()?

Answer: Use .indexOf() when we want to find the index of the first occurrence of a specific value in an array.
For example:

var arr = ['this', 'is', 'my', 'array', 'of', 'strings'];

console.log(arr.indexOf('my')); //2

We should use .findIndex() when we want to check a condition for each element of an array until the condition is met, and get the index of the first array element that passes said condition.

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

function isGreaterThanNine (num) {
  return num > 9; //returns a boolean value, true if num is greater than 9 else false 
}

console.log(myArray.findIndex(isGreaterThanNine)); //9

Do comment if you have any doubts or suggestions on this JS difference topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading