JavaScript Array findIndex() Method


The JavaScript array findIndex() method returns the index of first element of the given array that satisfies the provided function condition. It returns -1, if no element satisfies the condition.

The JavaScript Array findIndex() method returns the index of the first array element that satisfies the provided test function or else returns -1.

The findIndex() method executes the function once for each element present in the array:

  • If it finds an array element where the function returns a true value, findIndex() returns the index of that array element (and does not check the remaining values)
  • Otherwise it returns -1

Syntax

array.findIndex(function(currentValue, index, arr), thisValue)

Parameters: This method accepts five parameters as mentioned above and described below:

  • thisValue: This parameter is optional, if a value to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value.

Return value:It returns the array element index if any of the elements in the array pass the test, otherwise it returns -1.

Example

<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>

<p>Any ages above: <span id="demo"></span></p>

<script>
var ages = [4, 12, 16, 20];

function checkAdult(age) {
  return age >= document.getElementById("ageToCheck").value;
}

function myFunction() {
  document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
</script>

Example -