Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

JavaScript Array indexOf() method

Reference for JavaScript Array indexOf(): find the first index of a value with strict equality, the fromIndex argument, the -1 result and the NaN trap.

The indexOf() method returns the first index at which a given value is found in an array, or -1 if it is not there. It searches from the start (or from fromIndex) and compares with strict equality, the same as ===.

Use it when you need the position of a value. If you only want to know whether it is present, includes() reads better.

JavaScript
["a", "b", "c", "b"].indexOf("b"); // 1

Try it

JS Finding positions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Strict equality limits

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
indexOf(searchElement)
indexOf(searchElement, fromIndex)
Name Description
searchElement The value to locate, compared with ===.
fromIndex Optional. Index at which to start, default 0. A negative value counts from the end (length + fromIndex); if the result is below 0, the search starts at 0. If it is length or more, nothing is searched and -1 is returned.

Return value: the first matching index, or -1.

Exceptions: none for ordinary arrays.

Usage notes

  • -1 means "not found". It is also truthy, so if (arr.indexOf(x)) is a bug: it fails for index 0 and passes for -1. Compare explicitly: arr.indexOf(x) !== -1, or use includes().
  • Strict equality only. 1 and "1" differ, and objects match only by reference, so searching for a fresh { id: 1 } finds nothing. Use findIndex() for conditions.
  • NaN is never found, because NaN === NaN is false. Use includes(NaN) or findIndex(Number.isNaN).
  • Holes are skipped, so [ , "x"].indexOf(undefined) is -1, while an explicit undefined element is found.
  • Last occurrence: lastIndexOf() searches from the end.
  • All occurrences: call indexOf() repeatedly with previous + 1 as fromIndex, or use reduce() or a loop.
  • Strings have indexOf() too, with different arguments (substrings, not single elements).

Browser support

indexOf() is supported in every current browser and has been for a very long time.