findIndex()
ES6+Returns the index of the first element in the array that satisfies the provided testing function.
Syntax
array.findIndex(callback(element, index, array), thisArg)Parameters
callback Function Function to test each element
Return Value
The index of the first matching element, or -1
Examples
const numbers = [5, 12, 8, 130, 44];
const index = numbers.findIndex(x => x > 10);
console.log(index); 📌 When to Use
Use findIndex() when you need the position of an element, not the element itself. Essential for operations like splicing at a specific position, checking insertion points, or when you need to update an element in place.
⚠️ Common Mistakes
Forgetting that findIndex() returns -1 (not undefined) when no element is found
Using findIndex() when you only need to check existence - use some() instead
Checking findIndex() result with if(index) instead of if(index !== -1)
✅ Best Practices
Always check for -1 before using the index: if (idx !== -1) arr.splice(idx, 1)
Use indexOf() for simple primitive value lookups instead of findIndex()
Combine with splice() for removing or replacing items: arr.splice(findIndex(...), 1, newItem)
⚡ Performance Notes
findIndex() stops at the first match, making it efficient for finding a single element's position. For primitive values, indexOf() is slightly faster. If you need both the element and its index, use find() with a separate indexOf() or entries().
🌍 Real World Example
Updating an Item in a Shopping Cart
Find and update the quantity of a specific product in a shopping cart array
const cart = [
{productId: 101, name: 'Laptop', quantity: 1},
{productId: 102, name: 'Mouse', quantity: 2}
];
function updateQuantity(productId, newQuantity) {
const index = cart.findIndex(item => item.productId === productId);
if (index !== -1) {
cart[index].quantity = newQuantity;
return true;
}
return false; // Product not found
}
updateQuantity(102, 5); // Mouse quantity now 5