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.
["a", "b", "c", "b"].indexOf("b"); // 1
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
-1means "not found". It is also truthy, soif (arr.indexOf(x))is a bug: it fails for index0and passes for-1. Compare explicitly:arr.indexOf(x) !== -1, or useincludes().- Strict equality only.
1and"1"differ, and objects match only by reference, so searching for a fresh{ id: 1 }finds nothing. UsefindIndex()for conditions. NaNis never found, becauseNaN === NaNis false. Useincludes(NaN)orfindIndex(Number.isNaN).- Holes are skipped, so
[ , "x"].indexOf(undefined)is-1, while an explicitundefinedelement is found. - Last occurrence:
lastIndexOf()searches from the end. - All occurrences: call
indexOf()repeatedly withprevious + 1asfromIndex, or usereduce()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.