DEV Community

tutorials-kept-simple
tutorials-kept-simple

Posted on • Originally published at flexiple.com

findIndex method: JavaScript array

JavaScript methods are actions that can be performed on objects. Today, let us understand how the findIndex() method works. This method was added to the array.prototype() in the JavaScript ES6. The prototype constructor allows you to add new properties and methods to the Array() object.

Table of Contents

Syntax and explanation

The findIndex() method returns the index of the first element in array that satisfies the given testing function. If no element of the array satisfies the testing condition, it returns -1.

The syntax of the findIndex() method is as follows

findIndex(testfunc(currentValue, index, arr), thisValue)
Enter fullscreen mode Exit fullscreen mode

The above findIndex() method takes two arguments:
A. testfunc
B. thisValue

A. testFunc

The testFunc() is a function that is used to execute a condition on each element of the array until the function returns true, indicating that the element satisfying the condition was found.

The testFn() takes three arguments:

  • currentValue: This indicates the current element in the array being processed.
  • index: Indicates the index of the current element being processed.
  • arr: This is the array that the findIndex() was called upon.

B. thisValue

It is an optional argument that is passed to the function and used as its "this" value. If it is empty, the value "undefined" will be passed as its "this" value. In JavaScript, "this" keyword refers to the object it belongs to.

The findIndex() executes testFunc() for every element of the array and if true is returned by the testFunc(), findIndex() returns the index of that element and does not check for the rest of the array elements

Example Code

The following example uses findIndex() method to find the first occurrence of a prime number in a given array.

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start < 1) {
      return false;
    } else {
      start++;
    }
  }
  return element > 1;
}

console.log([4, 6, 16, 32].findIndex(isPrime));
//Output: -1, not found
console.log([4, 7, 6, 12].findIndex(isPrime));
//Output:  1 (array[1] is 7)
Enter fullscreen mode Exit fullscreen mode

Browser Support

  • Google Chrome 45.0 and above
  • Mozilla Firefox 25.0 and above
  • Microsoft Edge 12.0 and above
  • Internet Explorer does not Support findIndex() method
  • Safari 7.1 and above
  • Opera 32 and above

Top comments (0)