Membership with a position
Check whether a value occurs while retaining its position when present.
JavaScript · Function
Array.prototype.indexOf() returns the first index where a value occurs in an array, or -1 when it is absent. It optionally accepts a starting index and uses strict equality for matching.
Call this method with a value to search an array from the beginning, or provide a starting index. It checks elements in ascending order with strict equality, returns the first matching position, and returns -1 when no match exists; sparse-array holes are skipped.
indexOf(searchElement)
indexOf(searchElement, fromIndex)| Name | Type | Description |
|---|---|---|
searchElement | any | The value to locate in the array. |
fromIndex | integer | Optional zero-based starting index, converted to an integer. Negative values count from the end. |
The first index of searchElement in the array; -1 if not found.
const fruits = ["Apple", "Banana", "Apple"];
const position = fruits.indexOf("Banana");
console.log(position); // 1
console.log(fruits.indexOf("Cherry")); // -1
console.log(fruits.indexOf("Apple", 1)); // 2This finds the first matching value, reports absence with -1, and can begin searching at a specified index.
Check whether a value occurs while retaining its position when present.
Find a later occurrence by beginning the search after an earlier match.
Apply the method to objects that expose length and integer-keyed properties.
It returns the first index where the searched value occurs, or -1 when no element matches. Matching uses strict equality, equivalent to the === comparison algorithm.
Follow-up: How would you find NaN? Use Number.isNaN while scanning, or use includes when only a presence check is needed, because indexOf(NaN) always returns -1.
The optional fromIndex is converted to an integer and determines where the search starts. A negative value is counted from the end, while a value beyond the array length prevents searching.
Follow-up: What happens with a negative fromIndex smaller than -array.length? It is treated as 0, so the complete array is searched.
The method is generic: it only requires a this value with a length property and integer-keyed properties. Therefore, it can operate on array-like objects as well as actual arrays.
Follow-up: Does generic mean it works on every object? No; the object still needs a usable length and indexed properties for meaningful results.
Array.prototype.includes()Array.prototype.lastIndexOf()Array.prototype.findIndex()TypedArray.prototype.indexOf()