Array.prototype.indexOf()
indexOf(searchElement, fromIndex) Returns:
number · Updated March 13, 2026 · Array Methods array indexof search find
indexOf() searches an array from left to right and returns the first index where the given element is found. Returns -1 when the element is not found.
Syntax
indexOf(searchElement)
indexOf(searchElement, fromIndex)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
searchElement | any | — | The value to search for in the array |
fromIndex | number | 0 | The index to start searching from |
Examples
Basic usage
const fruits = ["apple", "banana", "orange", "banana", "melon"];
console.log(fruits.indexOf("banana"));
// 1
console.log(fruits.indexOf("grape"));
// -1
Using fromIndex
const letters = ["a", "b", "c", "b", "a"];
// Start searching from index 2
console.log(letters.indexOf("b", 2));
// 3
Finding all occurrences
const numbers = [1, 2, 3, 2, 1, 2, 3];
const target = 2;
const indices = [Global_Objects::eval];
let index = numbers.indexOf(target);
while (index !== -1) {
indices.push(index);
index = numbers.indexOf(target, index + 1);
}
console.log(indices);
// [1, 3, 5]
Common Patterns
Checking if an element exists
const users = ["alice", "bob", "charlie"];
if (users.indexOf("bob") !== -1) {
console.log("User found");
}
// User found
// Or simply
const exists = users.includes("bob");
console.log(exists);
// true
Removing specific occurrences
const items = ["a", "b", "c", "b", "d"];
const toRemove = "b";
const idx = items.indexOf(toRemove);
if (idx !== -1) {
items.splice(idx, 1);
}
console.log(items);
// ['a', 'c', 'b', 'd']
Strict Equality
indexOf uses strict equality (===) for comparison. Objects are compared by reference, not by value.
const objects = [{ id: 1 }, { id: 2 }];
const found = objects.indexOf({ id: 1 });
console.log(found);
// -1 — different object reference
// To find by property, use findIndex()
const foundByProp = objects.findIndex(obj => obj.id === 1);
console.log(foundByProp);
// 0
See Also
- array::includes — check if array contains an element
- array::findIndex — find index using a predicate function
- array::find — find the element itself