JavaScript Array keys() Method

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

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
      
       // Taking input as an array A 
       // containing some elements.
       var A = [ 5, 6, 10 ];
      
       // array.keys() method is called
       var iterator = A.keys();
      
       // printing index array using the iterator
       for (let key of iterator) {
        document.write(key + ' ');
       }
    </script>

    chevron_right

    
    

  • Output:
    0 1 2

The array.keys() method is used to return a new array iterator which contains the keys for each index in the given input array.

Syntax:

array.keys()

Parameters: This method does not accept any parameters.

Return Values: It returns a new array iterator.



Below example illustrate the Array keys() method in JavaScript:

  • Example:
    var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ];
    var iterator = A.keys(document.write(key + ' '));

    Output:

    0 1 2 3

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
   // Taking input as an array A 
   // containing some elements.
   var A = [ 'gfg', 'geeks', 'cse', 'geekpro' ];
  
   // array.keys() method is called
   var iterator = A.keys();
  
   // printing index array using the iterator
   for (let key of iterator) {
    document.write(key + ' ');
   }
</script>

chevron_right


Output:

0 1 2 3 

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
  // Taking input as an array A
  // containing some elements
  var A = [ 'gfg', 'geeks', 'cse', 'geekpro', '', 1, 2 ];
  
  // array.keys() method is called
  var iterator = A.keys();
  
  // Printing index array using the iterator
  for (let key of iterator) {
    document.write(key + ' ');
  }
</script>

chevron_right


Output:

0 1 2 3 4 5 6 

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

  • Google Chrome 38.0
  • Microsoft Edge 12.0
  • Mozilla Firefox 28.0
  • Safari 8.0
  • Opera 25.0

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.