Array.keys()

The Array.keys() method in JavaScript returns a new array iterator object that contains the keys (indices) for each index in the array.

Syntax

</>
Copy
array.keys()

Parameters

The keys() method does not accept any parameters.

Return Value

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


Examples

1. Iterating Over Array Indices

This example demonstrates how to use the keys() method to iterate over the indices of an array.

</>
Copy
const array = ['a', 'b', 'c'];

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

Output

0
1
2
  1. The array.keys() method creates an iterator for the indices of the array.
  2. Using a for...of loop, the indices 0, 1, and 2 are logged to the console.

2. Converting Iterator to an Array

The Array.from() method can be used to convert the iterator returned by keys() into an array of indices.

</>
Copy
const array = ['x', 'y', 'z'];

const indices = Array.from(array.keys());
console.log(indices);

Output

[0, 1, 2]

Here, Array.from() converts the iterator into a standard array containing the indices of the original array.

3. Using keys() on Sparse Arrays

The keys() method includes all indices of the array, even for empty slots in sparse arrays.

</>
Copy
const sparseArray = [10, , 30];

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

Output

0
1
2

Even though the second slot is empty, the keys() method iterates over all indices, including 1.

4. Combining keys() with entries()

You can combine keys() with entries() to retrieve both indices and values.

</>
Copy
const array = ['apple', 'banana', 'cherry'];

const iterator = array.keys();
for (const key of iterator) {
    console.log(key, array[key]);
}

Output

0 apple
1 banana
2 cherry

By accessing array[key], you can retrieve the value corresponding to each key.