Skip to content
Related Articles

Related Articles

JavaScript Array indexOf() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jan, 2022
View Discussion
Improve Article
Save Article

Below is the example of the Array indexOf() method. 
 

  • Example: 
     

javascript




<script>
    var name = [ 'gfg', 'cse', 'geeks', 'portal' ];
 
    a = name.indexOf('gfg')
 
    // Printing result of method
    document.write(a);
</script>

  • Output: 
     
0

The arr.indexOf() method is used to find the index of the first occurrence of the search element provided as the argument to the method. 
Syntax: 
 

array.indexOf(element, start)

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

  • element: This parameter holds the element which index will be return.
  • start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0.

Return value: This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.
Below examples illustrate the Array indexOf() method in JavaScript: 
 

  • Example 1: In this example the method will searched for the element 2 in that array return that element index. 
     
Input : [1, 2, 3, 4, 5].indexOf(2);
Output: 1
  • Example 2: In this example the method will searched for the element 9 in that array if not found then return -1. 
     
Input : [1, 2, 3, 4, 5].indexOf(9);
Output: -1

Code for the above method is provided below:
Program 1: 
 

javascript




<script>
 
    // Taking input as an array A
    // having some elements.
    var A = [ 1, 2, 3, 4, 5 ];
 
    // indexOf() method is called to
    // test whether the searching element
    // is present in given array or not.
    a = A.indexOf(2)
 
    // Printing result of method.
    document.write(a);
</script>

Output: 
 

1

Program 2: 
 

javascript




<script>
    // Taking input as an array A
    // having some elements.
    var name = [ 'gfg', 'cse', 'geeks', 'portal' ];
 
    // indexOf() method is called to
    // test whether the searching element
    // is present in given array or not.
    a = name.indexOf('cat')
 
    // Printing result of method
    document.write(a);
</script>

Output: 
 

-1

Supported Browsers: The browsers supported by JavaScript Array indexOf() method are listed below: 
 

  • Google Chrome 1 and above
  • Edge 12 and above
  • Firefox 1.5 and above
  • Internet Explorer 9 and above
  • Opera 9.5 and above
  • Safari 3 and above

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!