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

← All JS array methods · TypeScript vs JavaScript