When should I use .findIndex() vs .indexOf()?



When should I use .findIndex() vs .indexOf()?


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

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

console.log(myArrayOfStrings.indexOf('my')); //logs `2` to the console because the string value `'my'` is at the 2nd index (arrays in JS start at 0)

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.
For example:

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, false if num is less than or equal to 9

console.log(myArray.findIndex(isGreaterThanNine)); //9 is logged to the console as the value at the 9th index is the first value that passes the condition provided by the isGreaterThanNine function


That would be the first occurrence of the value in the array. If there are multi instances of that value, they will never be found. findIndex() does nothing to solve this dilemma. Obviously it represents another problem to solve.