JavaScript indexOf(): Get the First Index of a Value in an Array

The JavaScript indexOf() method is used to find the first index of a specified value in an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
<p>Index of "UK" = <span id="codescracker"></span></p>

<script>
   const countries = ["Luxembourg", "USA", "Australia", "UK", "Finland", "Canada"];
   let x = countries.indexOf("UK");
   
   document.getElementById("codescracker").innerHTML = x;
</script>
   
</body>
</html>
Output

Index of "UK" =

JavaScript indexOf() syntax

The syntax of the indexOf() method in JavaScript is:

array.indexOf(item, startIndex)

The item refers to the item, value, or element for which we need the index number. And the startIndex parameter is optional and is used to start searching for specified item from a particular index number. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
<p>Index = <span id="myspan"></span></p>

<script>
   const ctrs = ["Luxembourg", "USA", "Australia", "UK", "USA", "Canada"];
   let myi = ctrs.indexOf("USA", 2);
   
   document.getElementById("myspan").innerHTML = myi;
</script>
   
</body>
</html>
Output

Index =

Note: Indexing starts with 0. Therefore, Australia is at index number 2.

What if the specified element is not available in the given array?

Let's check it out. What will happen if the specified item is not available in the given array?

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
<p>Index of "UAE" = <span id="myspn"></span></p>

<script>
   const crs = ["Luxembourg", "USA", "Australia", "UK", "USA", "Canada"];
   let i = crs.indexOf("UAE", 2);
   
   document.getElementById("myspn").innerHTML = i;
</script>
   
</body>
</html>
Output

Index of "UAE" =

That means the indexOf() method returns -1 if the specified item is not found. Therefore, we can use JavaScript code like this to avoid printing the returned value itself.

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <script>
      const c = ["Luxembourg", "USA", "Australia", "UK", "USA", "Canada"];
      let nx = c.indexOf("UAE", 2);

      if(nx == -1)
         console.log("The country \"UAE\" is not available in the list.");
      else
         console.log("Index of \"UAE\" = ", nx);
   </script>
   
</body>
</html>

The snapshot given below shows the sample output produced by the above JavaScript example:

javascript indexof array

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!