JavaScript indexOf() | Get 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="fresherearth"></span></p>

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

Index of "UK" =

JavaScript indexOf() Syntax

The syntax of indexOf() method in JavaScript is:

array.indexOf(item, startIndex)

The item refers to the item or value or element of which, we need to get the index number. And the startIndex parameter is optional that is used to start searching for specified item from 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 Specified Element is not Available in 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 specified item does 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 above JavaScript example:

javascript indexof array

JavaScript Online Test


« Previous Tutorial Next Tutorial »