Home

indexOf

IndexOf is a method name commonly used in JavaScript to locate the position of a value or substring within a sequence. It is defined for both strings and arrays. The method returns the index of the first match, or -1 if no match is found. An optional fromIndex parameter specifies the starting position for the search.

For arrays, indexOf(searchElement[, fromIndex]) searches from fromIndex (default 0) and returns the first index where searchElement

For strings, indexOf(searchValue[, fromIndex]) searches for the first occurrence of the substring searchValue starting at fromIndex

Common uses include checking presence (for example, indexOf(...) !== -1) and locating positions for substring or element

is
strictly
equal
(===)
to
an
element
of
the
array.
If
not
found,
it
returns
-1.
A
negative
fromIndex
counts
from
the
end
of
the
array.
The
comparison
uses
strict
equality,
so
values
like
NaN
are
not
considered
equal
to
NaN.
(default
0).
If
the
substring
is
found,
the
function
returns
its
starting
index;
otherwise
it
returns
-1.
For
strings,
a
negative
fromIndex
is
treated
as
0.
extraction.
The
operation
is
linear
in
the
length
of
the
sequence,
making
it
a
simple
but
potentially
costly
search
for
large
arrays
or
long
strings.
In
modern
JavaScript,
a
related
method
called
includes
returns
a
boolean
indicating
presence,
and
lastIndexOf
finds
the
last
occurrence.
IndexOf
remains
widely
supported
and
frequently
used
in
code
that
predates
includes.