Array.indexOf()
The Array.indexOf()
method in JavaScript is used to find the first occurrence of a specified element in an array. It returns the index of the element if found, or -1
if the element is not present.
Syntax
indexOf(searchElement)
indexOf(searchElement, fromIndex)
Parameters
Parameter | Description |
---|---|
searchElement | The element to locate in the array. |
fromIndex (optional) | The index to start the search from. Defaults to 0 . If fromIndex is negative, it is treated as array.length + fromIndex . |
Return Value
The indexOf()
method returns the first index at which the specified searchElement
is found, or -1
if the element is not found in the array.
Examples
1. Finding the Index of an Element
This example demonstrates how to find the first occurrence of an element in an array.
const fruits = ['apple', 'banana', 'cherry', 'apple'];
console.log(fruits.indexOf('apple'));
console.log(fruits.indexOf('cherry'));
Output
0
2
fruits.indexOf('apple')
returns0
as the first occurrence of'apple'
is at index0
.fruits.indexOf('cherry')
returns2
as'cherry'
is located at index2
.
2. Using fromIndex
to Start the Search
Here, the fromIndex
parameter specifies where the search should start.
const fruits = ['apple', 'banana', 'cherry', 'apple'];
console.log(fruits.indexOf('apple', 1));
console.log(fruits.indexOf('banana', 2));
Output
3
-1
fruits.indexOf('apple', 1)
starts the search from index1
and finds'apple'
at index3
.fruits.indexOf('banana', 2)
starts the search from index2
. Since'banana'
is not present after index2
, it returns-1
.
3. Searching with Negative fromIndex
A negative fromIndex
indicates the offset from the end of the array.
const fruits = ['apple', 'banana', 'cherry', 'apple'];
console.log(fruits.indexOf('apple', -2));
console.log(fruits.indexOf('cherry', -3));
Output
3
2
In the first example, fruits.indexOf('apple', -2)
starts searching from the second-to-last element and finds 'apple'
at index 3
.
In the second example, fruits.indexOf('cherry', -3)
starts searching from the third-to-last element and finds 'cherry'
at index 2
.
4. Element Not Found
When the searchElement
is not found, the indexOf()
method returns -1
.
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.indexOf('grape'));
Output
-1
Since 'grape'
is not in the fruits
array, the method returns -1
.