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
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 thanindexOf(x) !== -1. - For objects and more complex conditions, use
findIndex().
Related entries
#- Array.prototype.includes()Checks whether an array contains the given value.
- Array.prototype.findIndex()Returns the index of the first element that matches a condition, or -1.
- String.prototype.indexOf()Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.
- Array.prototype.lastIndexOf()Returns the index of the last occurrence of a value in the array, or -1 when it isn’t there.
Spotted a mistake or missing an example? Write to us.