search
Array.prototype.indexOf
Returns the first index where searchElement is strictly equal (===) to an array item, or -1. Reach for it for a fast, exact primitive lookup — but not for objects or NaN.
arr.indexOf(searchElement[, fromIndex]) Parameters
| Parameter | Purpose |
|---|---|
| searchElement | Value to match with strict equality |
| fromIndex | Index to start from; negative counts from the end |
Examples
console.log(['a','b','c','b'].indexOf('b')); Logs: 1
console.log(['a','b','c'].indexOf('z')); Logs: -1
console.log(['a','b','c','b'].indexOf('b', 2)); Logs: 3
console.log([NaN, 1, 2].indexOf(NaN)); Logs: -1 (NaN !== NaN, use findIndex or includes)
Gotcha
Uses strict === so `indexOf(NaN)` is always -1 — use `includes` or `findIndex` for NaN. Objects are matched by reference, not shape.
Related methods
Array.prototype.includes
Returns true if the array contains searchElement using SameValueZero equality (ES2016). Reach for it as the readable boolean alternative to `indexOf(x) !== -1`.
Array.prototype.findIndex
Returns the index of the first element for which the callback returns truthy, or -1 if none match. Reach for it when you need the position — e.g. to splice or replace.
Array.prototype.find
Returns the first element for which the callback returns truthy, or undefined if none match. Reach for it when you need the matching item itself, not just its index.
Array.prototype.findLast
Walks the array from the END and returns the last element for which the callback returns truthy (ES2023). Reach for it when the most recent matching entry is what you want.