JavaScriptArrays

Array.prototype.indexOf()

Returns the index of the first occurrence of a value, or -1.

Returns
The index of the first occurrence, or -1.
Changes the original
No
On this page

Example

#
JavaScript
const colors = ['red', 'green', 'blue', 'green']

console.log(colors.indexOf('green'))
console.log(colors.lastIndexOf('green'))
console.log(colors.indexOf('pink'))
Console
1
3
-1

Definition and usage

#

The indexOf() method looks for the given value and returns the index of its first occurrence. If the value isn’t in the array, it returns -1.

It compares strictly, like ===. So it won’t find the number 1 if you search for the string "1", and it won’t find NaN. To search by a condition, such as an object with a given id, use findIndex().

Its counterpart, lastIndexOf(), searches from the end and returns the index of the last occurrence.

Syntax

#
Syntax
array.indexOf(searchElement)
array.indexOf(searchElement, fromIndex)

Parameters

#
  • searchElement

    any value

    The value to search for.
  • fromIndex

    optional

    The index to start searching from.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To just check for presence, includes() reads better than indexOf(x) !== -1.
  • For objects and more complex conditions, use findIndex().

Related entries

#

Spotted a mistake or missing an example? Write to us.