JavaScript Tutorial JavaScript References

JavaScript Array - indexOf() Method



The JavaScript indexOf() method returns the position of the first found occurrence of specified element in the array, or -1 if it is not present.

Syntax

Array.indexOf(searchElement, fromIndex)

Parameters

searchElement Required. Specify the element to search for.
fromIndex Optional. Specify the index from which to start the search. If it is greater than or equal to the array's length, -1 is returned. If it is a negative number, it is taken as the offset from the end of the array. Default: 0.

Note: If fromIndex is negative, the array is still searched from front to back. If it is provided as 0, then the whole array will be searched.

Return Value

Returns the index number for first occurrence of specified element. Returns -1 if there is no such occurrence.

Example:

The example below shows the usage of indexOf() method.

//creating an array
var Arr = [10, 20, 30, 40];
var txt;

txt = "Arr.indexOf(5) = " + Arr.indexOf(5) + "<br>";
txt = txt + "Arr.indexOf(10) = " + Arr.indexOf(10) + "<br>";
txt = txt + "Arr.indexOf(20) = " + Arr.indexOf(20) + "<br>";
txt = txt + "Arr.indexOf(25) = " + Arr.indexOf(25) + "<br>";
txt = txt + "Arr.indexOf(10, 1) = " + Arr.indexOf(10, 1) + "<br>";
txt = txt + "Arr.indexOf(30, -3) = " + Arr.indexOf(30, -3) + "<br>";

The output (value of txt) after running above script will be:

Arr.indexOf(5) = -1
Arr.indexOf(10) = 0
Arr.indexOf(20) = 1
Arr.indexOf(25) = -1
Arr.indexOf(10, 1) = -1
Arr.indexOf(30, -3) = 2

Example: Finding all the occurrences of an element

In the example below, the indexOf() method is used to find the indices of all occurrences of a given element.

//creating an array
var Arr = ['a', 'b', 'a', 'c', 'a', 'd'];
var txt = "";

var element = 'a';
//finding indices of all occurrences of 'a'
var idx = Arr.indexOf(element);
while (idx != -1) {
  txt = txt + "Found at: " + idx + "<br>";
  idx = Arr.indexOf(element, idx + 1);
}

The output (value of txt) after running above script will be:

Found at: 0
Found at: 2
Found at: 4

❮ JavaScript - Array Object