JavaScript (ES2026) reference · Array Methods
JavaScript Array indexOf() Method
Return the first index at which a value is found (using ===), or -1 if it isn't in the array.
JavaScript (ES2026) Since ES5
Syntax
array.indexOf(searchElement, fromIndex)
Parameters
| Parameter | Description |
|---|---|
searchElement |
The value to look for. |
fromIndex optional |
Index to start from. Default: 0 |
Return value
An index, or -1.
Examples
const letters = ["a", "b", "c", "b"];
console.log(letters.indexOf("b"), letters.indexOf("b", 2), letters.indexOf("z"));
Output
1 3 -1
const items = ["x", "y"];
if (items.indexOf("y") !== -1) console.log("found");
if (items.includes("y")) console.log("found (clearer)");
Output
found found (clearer)
Version history
| Version | Change |
|---|---|
| JavaScript ES5 | Added |
In other languages
list.index()· Python
Related
array.lastIndexOf()· Return the last index at which a value is found (using ===), searching backwards, or -1 if it isn't there.array.includes()· Return true if the array contains a value, using SameValueZero equality (so it finds NaN, unlike indexOf).array.findIndex()· Return the index of the first element that passes a test function, or -1 if none does.- JavaScript Arrays · tutorial
- JavaScript Array Methods · tutorial