JavaScript Array keys()

The keys() method returns a new Array Iterator object that contains the keys for each element in the array.

Example


keys() Syntax

The syntax of the keys() method is:

arr.keys()

Here, arr is an array.


keys() Parameters

The keys() method does not take any parameters.


keys() Return Value

  • Returns a new Array iterator object.

Notes: The keys() method does not:

  • change the original array.
  • ignore empty array elements.

Example 1: Using keys() Method

Output

0
1
2
3

In the above example, we have used the keys() method to find out the key of each element in the languages array.

Here, languages.keys() returns an Array Iterator object whose value is stored in iterator.

And finally, we have looped through iterator that prints the key for each element of language.


Example 2: 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:

Output

0
1
2
3
4

Recommended Reading: JavaScript Array values()