Array.prototype.keys()
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Thekeys()
method ofArray
instances returns a newarray iterator object that contains the keys for each index in the array.
Try it
const array1 = ["a", "b", "c"];const iterator = array1.keys();for (const key of iterator) { console.log(key);}// Expected output: 0// Expected output: 1// Expected output: 2
Syntax
keys()
Parameters
None.
Return value
A newiterable iterator object.
Description
When used onsparse arrays, thekeys()
method iterates empty slots as if they have the valueundefined
.
Thekeys()
method isgeneric. It only expects thethis
value to have alength
property and integer-keyed properties.
Examples
Using keys() on sparse arrays
UnlikeObject.keys()
, which only includes keys that actually exist in the array, thekeys()
iterator doesn't ignore holes representing missing properties.
const arr = ["a", , "c"];const sparseKeys = Object.keys(arr);const denseKeys = [...arr.keys()];console.log(sparseKeys); // ['0', '2']console.log(denseKeys); // [0, 1, 2]
Calling keys() on non-array objects
Thekeys()
method reads thelength
property ofthis
and then yields all integer indices between 0 andlength - 1
. No index access actually happens.
const arrayLike = { length: 3,};for (const entry of Array.prototype.keys.call(arrayLike)) { console.log(entry);}// 0// 1// 2
Specifications
Specification |
---|
ECMAScript® 2026 Language Specification # sec-array.prototype.keys |