JavaScript Array indexOf() method

The indexOf() method returns the first index (position) of a specified value. It is used to search the position of a particular element in a given array.

The indexOf() method returns -1 if the value is not found.

The index position of first element in an array is always start with zero. 

This method is case-sensitive.

In this tutorial, you will learn about the JavaScript Array indexOf() method with the help of examples.


array.indexOf(item, start)

Parameters: This method accepts two parameters as mentioned above and described below: 

item – It represent the element to be searched.

start – It represent the index position from where search starts. It is optional. If the index is greater than or equal to the array’s length, -1 is returned, which means the array will not be searched.

The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.

Negative start values counts from the last element (but still searches from right to left).

Return Value

The index (position) of the first item found. -1 if the item is not found.


Below are the examples of the Array indexOf() method. 

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

// expected output: -1

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
var priceList = [10, 8, 2, 31, 10, 1, 65];

// indexOf() returns the first occurance
var index1 = priceList.indexOf(31);
console.log(index1); // 3

var index2 = priceList.indexOf(10);
console.log(index2); // 0

// second argument specifies the search's start index
var index3 = priceList.indexOf(10, 1);
console.log(index3); // 4

// indexOf returns -1 if not found
var index4 = priceList.indexOf(69.5);
console.log(index4); // -1