Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

JavaScript Array keys() method

Reference for JavaScript Array keys(): get an iterator over the indexes of an array, including holes, and turn it into an array with spread or Array.from().

The keys() method returns a new array iterator that produces the index of each position in the array: 0, 1, 2 and so on. The values themselves are not part of the result.

Because the result is an iterator, not an array, you consume it with for...of, spread ([...arr.keys()]) or Array.from(). Unlike Object.keys(), which returns strings and skips holes, array.keys() returns numbers and includes the empty slots.

JavaScript
[...["a", "b", "c"].keys()]; // [0, 1, 2]

Try it

JS Looping over indexes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Holes and Object.keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
keys()

Parameters: none.

Return value: a new array iterator object that yields each index as a number. It is iterable itself, so it[Symbol.iterator]() === it.

Exceptions: none for ordinary arrays.

Usage notes

  • Holes are included. The iterator visits every index from 0 to length - 1, whether or not a value exists there. Object.keys() only lists indexes that really exist, and returns them as strings.
  • Numbers, not strings. Index values are numbers, which is why arr[index] and arithmetic work without conversion.
  • Live view. The iterator is lazy and checks the array's length as it goes, so elements added during a loop are reached.
  • Generating a range: [...Array(5).keys()] gives [0, 1, 2, 3, 4]. That works because keys() includes holes. Array.from({ length: 5 }, (_, i) => i) is the more explicit alternative.
  • Single use. An iterator is exhausted after one pass; call keys() again for another.
  • Newer iterator helpers (map(), filter(), take() on iterators) can be chained on the result in environments that support them; check a compatibility table.
  • Siblings: values() yields elements, entries() yields [index, value] pairs. A plain for loop is fine when you just need the index.

Browser support

keys() is supported in every current browser. The iterator helper methods mentioned above are more recent.