How to Use findIndex in JavaScript: Syntax and Examples
Use the
findIndex method on an array to get the index of the first element that satisfies a condition defined by a callback function. It returns the index if found, or -1 if no element matches.Syntax
The findIndex method is called on an array and takes a callback function as its argument. This callback receives each element, its index, and the whole array, and should return true for the element you want to find.
- callback(element, index, array): Function to test each element.
- Returns: The index of the first element that passes the test, or
-1if none do.
javascript
array.findIndex((element, index, array) => {
// return true when condition is met
});Example
This example finds the index of the first number greater than 10 in an array.
javascript
const numbers = [4, 9, 16, 25]; const index = numbers.findIndex(num => num > 10); console.log(index);
Output
2
Common Pitfalls
One common mistake is forgetting that findIndex returns -1 if no element matches, which can cause bugs if not checked. Also, the callback must return a boolean; returning a non-boolean can lead to unexpected results.
Another pitfall is using findIndex on an empty array or without a proper callback, which will always return -1.
javascript
const arr = [1, 2, 3]; // Wrong: callback returns non-boolean values const wrongIndex = arr.findIndex(num => num > 5 ? 'yes' : 'no'); console.log(wrongIndex); // Output: -1 because 'yes' and 'no' are truthy but not boolean // Right: callback returns boolean const rightIndex = arr.findIndex(num => num > 5); console.log(rightIndex); // Output: -1
Output
-1
-1
Quick Reference
| Method | Description | Return Value |
|---|---|---|
| findIndex(callback) | Finds index of first element matching condition | Index (number) or -1 if not found |
| callback(element) | Function to test each element | Boolean (true to match) |
| Returns -1 | If no element matches the condition | Number -1 |
Key Takeaways
Use findIndex to get the index of the first array element that meets a condition.
The callback function must return a boolean to indicate a match.
If no element matches, findIndex returns -1, so always check for this.
findIndex does not change the original array.
It is useful for finding positions without looping manually.