Array.prototype.keys()

keys()
Returns: Array Iterator · Updated March 13, 2026 · Array Methods
array iterator keys es6

The keys() method returns a new Array iterator object containing the keys (indices) of each array element. Introduced in ES6, this method provides a clean way to iterate over array indices using for...of loops, avoiding the older for loop syntax.

Syntax

array.keys()

Takes no parameters and returns an iterator object.

Parameters

None. The method accepts no parameters.

Examples

Basic usage with for…of

const fruits = ["apple", "banana", "cherry"];

for (const index of fruits.keys()) {
  console.log(index);
}
// 0
// 1
// 2

Using with spread operator

const numbers = [10, 20, 30];

const indices = [...numbers.keys()];
console.log(indices);
// [0, 1, 2]

Working with sparse arrays

Unlike forEach(), keys() only iterates over indices that actually exist:

const sparse = [1, , 3];
console.log([...sparse.keys()]);
// [0, 1, 2]

Parallel array iteration

const names = ["Alice", "Bob", "Carol"];
const ages = [25, 30, 35];

for (const i of names.keys()) {
  console.log(`${names[i]} is ${ages[i]} years old`);
}
// Alice is 25 years old
// Bob is 30 years old
// Carol is 35 years old

Using Array.from with transformation

const data = ['a', 'b', 'c'];

// Create object with index as key
const indexed = Array.from(data.keys()).reduce((acc, i) => {
  acc[i] = data[i];
  return acc;
}, {});
console.log(indexed); // { 0: 'a', 1: 'b', 2: 'c' }

Finding indices matching condition

const scores = [65, 90, 75, 82, 55];

const passingIndices = [...scores.keys()].filter(i => scores[i] >= 70);
console.log(passingIndices); // [1, 2, 3]

Practical: updating specific indices

const items = ['a', 'b', 'c', 'd', 'e'];

// Double values at even indices
const indicesToUpdate = [...items.keys()].filter(i => i % 2 === 0);
indicesToUpdate.forEach(i => {
  items[i] = items[i] + items[i];
});
console.log(items); // ['aa', 'b', 'cc', 'd', 'ee']

Common Patterns

Reconstructing array with modifications

const original = [1, 2, 3, 4, 5];
const doubled = [...original.keys()].map(i => original[i] * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

See Also