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

Unlike methods that return values, .keys() focuses purely on the positions within the array.

1. Basic Syntax

array.keys()

The method takes no arguments. Because it returns an iterator, you cannot see the results immediately by logging the return value; you must loop through it or convert it to an array.

2. Basic Usage

To see the keys, the most common approach is to use a for...of loop or the spread operator.

const fruits = ['apple', 'banana', 'cherry'];
const iterator = fruits.keys();

for (const key of iterator) {
  console.log(key);
}
// Output: 0, 1, 2

3. Handling Sparse Arrays

A key feature of .keys() is how it handles “holes” (sparse arrays). Unlike Object.keys(), which ignores holes, the Array.prototype.keys() method includes them.

const arr = ['a', , 'c']; // Index 1 is an empty hole

console.log(Object.keys(arr));      // ["0", "2"] (Skips the hole)
console.log([...arr.keys()]);      // [0, 1, 2]   (Includes the hole)

4. Why use .keys()?

  • Range Generation: It is a clever way to generate a sequence of numbers.
  • Compatibility: It allows you to use the same iteration logic for Arrays, Maps, and Sets (which all have a .keys() method).
  • Memory Efficiency: Since it returns an iterator, it doesn’t create a full copy of the indices in memory until you specifically ask for them.

5. Difference: Array.keys() vs. Object.keys()

This is a common point of confusion. The behavior differs significantly when dealing with “holes” in an array.

[Image comparison of Array.keys vs Object.keys on sparse arrays]

const sparseArray = ['a', , 'c']; // Index 1 is empty

console.log(Object.keys(sparseArray));    // ["0", "2"] (Skips the hole)
console.log([...sparseArray.keys()]);     // [0, 1, 2]   (Includes the hole)

6. Practical Use Case: Generating a Range

You can combine the Array constructor with .keys() to quickly generate a sequence of numbers without manually typing them.

// Create an array of numbers from 0 to 9
const range = [...Array(10).keys()];

console.log(range); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Categorized in:

Javascript Array Methods,