JavaScript Array findIndex()
Example 1
Find the first element with a value over 18:
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
Try it Yourself »
Definition and Usage
The findIndex()
method executes a function for each array element.
The findIndex()
method returns the index (position) of the first element that passes a test.
The findIndex()
method returns -1 if no match is found.
The findIndex()
method does not execute the function for empty array elements.
The findIndex()
method does not change the original array.
Syntax
array.findIndex(function(currentValue, index, arr), thisValue)
Parameters
Parameter | Description |
function() | Required. A function to be run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
Return Value
Type | Description |
A number |
The index of the first element that passes the test. Otherwise -1. |
More Examples
Find the first element with a value above an input value:
<p><input type="number" id="toCheck" value="18"></p>
<button onclick="myFunction()">Test</button>
<p>Any values above: <span id="demo"></span></p>
<script>
const numbers = [4, 12, 16, 20];
function checkValue(x) {
return x > document.getElementById("toCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.findIndex(checkValue);
}
</script>
Try it Yourself »
Browser Support
findIndex()
is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
is not supported in Internet Explorer 11 (or earlier).