Skip to content

JavaScript Array keys() | Method

  • by

JavaScript Array keys() method is used to create a new iterator object which holds the key for every index in the Array. This method returns an Array Iterator object with the keys of an array and does not change the original array.

array.keys()

JavaScript Array keys()

A simple example code gets an Array Iterator object that contains the keys and loops through it.

<!DOCTYPE html>
<html>
<body>
  <script>
    let words = ["Apple", "Ball", "Cat", "Dog"];

    // returns an Array Iterator object that contains the keys
    let iterator = words.keys();
    console.log(iterator)

    // looping
    for (let key of iterator) {
      console.log(key);
    }

  </script>

</body>
</html>

Output:

JavaScript Array keys Method

More example

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

Using key() Method in Array with Holes

The iterator object doesn’t skip holes in the array. It also holds the key for empty slots in the array. For example:

let vehicle = ["car", "bus", , "van", "truck"];

// returns an Array Iterator Object that contains keyslet iterator = vehicle.keys();

// looping through the iterator object
for (let key of iterator) {
  console.log(key);
}

Output:

0
1
2
3
4

Do comment if you have any doubts or suggestions on this JS Array method tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *