• JavaScript Video Tutorials

JavaScript - Array indexOf() Method



The JavaScript Array indexOf() method is used to return the first occurrence index of a specified element within an array (if it is present at least once). If the element is not present in the array, it returns −1.

By default, this method starts the search from the first element to the last element. However, if you pass a starting index, the search begins from that specific index and moves towards the ending of the array.

In addition, if you pass a negative value as the starting index, it starts counting values from the last element, but the search still begins from left to right.

Syntax

Following is the syntax of JavaScript Array indexOf() method −

array.indexOf(searchElement, fromIndex);

Parameters

This method accepts two parameters. The same is described below −

  • searchElement − This specifies the element to locate within the array.
  • fromIndex (Optional) − This specifes the index at which to start the search. By default, the search starts from the beginning of the array.

Return value

This method the first index at which the element is found in the array, if the searchElement is found. Else, −1.

Examples

Example 1

In the following example, we are fetching the first occurrence index of “2” in the specified array using the JavaScript Array indexOf() method.

<html>
<body>
   <p id="demo"></p>
   <script>
      const numbers = [2, 5, 6, 2, 7, 9, 6];
      const result = numbers.indexOf(2);
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

As we can see in the output, the last occurrence index of “2” is 0.

0

Example 2

Here, we are trying to fetch the the first occurrence index of “10” which is not present in the specified array −

<html>
<body>
   <p id="demo"></p>
   <script>
      const numbers = [2, 5, 6, 2, 7, 9, 6];
      const result = numbers.indexOf(10);
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

As there is no element “10” in the array, the result will be −1.

-1

Example 3

In the below example, we are passing the second argument “3” to the indexOf() method. It searches for the element "6" starting from index 3 onwards in the array numbers −

<html>
<body>
   <p id="demo"></p>
   <script>
      const numbers = [2, 5, 6, 2, 7, 9, 6];
      const result = numbers.indexOf(6, 3);
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

The first occurrence of element 6 from index position 3 is “6”.

6

Example 4

It counts 5 positions from the end of the array and starts searching left to right for the element '2' −

<html>
<body>
   <p id="demo"></p>
   <script>
      const numbers = [2, 5, 6, 2, 7, 9, 6];
      const result = numbers.indexOf(2, -5);
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

3
Advertisements