• JavaScript Video Tutorials

JavaScript - Array keys() Method



The JavaScript Array.keys() method returns a new array iterator that contains the keys (i.e. indices) of each element in the specified array. These keys represent the indices or positions of the elements in the array.

The Array.keys() method does not overwrite the original array instead; it returns the result in a new array. This method ignores empty array elements.

Syntax

Following is the syntax of JavaScript Array keys() method −

array.keys()

Parameters

This method does not accept any parameters.

Return value

This method returns a new Array Iterator object that contains the keys for each index in the array.

Examples

Example 1

In the following example, we are using the JavaScript Array keys() method to iterate over the indices (keys) of the animals array.

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];
      const keysIterator = animals.keys();

      for (const key of keysIterator) {
         document.write(key + "<br>");
      }
   </script>
</body>
</html>

Output

After executing the program, the indices of the array elements will printed.

0
1
2
3
4

Example 2

Here, we are using from() method to convert the keys iterator into an array of keys for the “numbers” array −

<html>
<body>
   <script>
      const numbers = [18, 25, 13, 16, 22, 15];

      const result = Array.from(numbers.keys());
      document.write(result);
   </script>
</body>
</html>

Output

The result array contains the keys (indices) for the "numbers" array.

0,1,2,3,4,5
Advertisements