Skip to content
jshacks.dev
Fundamentals

JavaScript Array keys Explained With Clear Examples

Array keys() returns an iterator over indexes, including empty slots of a sparse array. See how it differs from Object.keys with exact output.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, TypeScript and npm logos.

Ask for the keys of an array and you get an iterator, not an array, and that iterator includes indexes that Object.keys() leaves out. The two functions share a name pattern and almost nothing else, which is why swapping one for the other in a refactor changes the result for sparse arrays and changes the type for everyone. This post explains what keys() returns, how it treats holes, how to turn it into an array, and the few cases where it is the right tool. Examples run on Node.js 24, and the sibling iterators are covered in [the post on values()](/library/javascript-array-values).

What keys() returns

array.keys() takes no arguments and returns an Array Iterator that yields each index from 0 to length - 1 as a number. It is available in every current engine and has been part of the language since ES2015.

JavaScript
const letters = ["a", "b", "c"];
const it = letters.keys();

console.log(it.next());
console.log(it.next());
console.log([...it]);
console.log(it.next());
Text
{ value: 0, done: false }
{ value: 1, done: false }
[ 2 ]
{ value: undefined, done: true }

Three details show up here. The values are numbers, not strings, unlike the keys from Object.keys(). The spread consumed the remaining item, so the iterator is now finished. And an exhausted iterator keeps answering done: true, so it cannot be rewound. Call keys() again for a fresh one.

Turning the iterator into something usable

Most callers want an array of indexes or a loop. Both are one line.

JavaScript
const items = ["x", "y", "z"];

console.log(Array.from(items.keys()));
console.log([...items.keys()]);

for (const i of items.keys()) {
  console.log(i, items[i]);
}
Text
[ 0, 1, 2 ]
[ 0, 1, 2 ]
0 x
1 y
2 z

Array.from() and spread produce the same result. The for...of form is the most common real use: it gives you an index without the for (let i = 0; ...) boilerplate and without allocating an array of indexes first, because the iterator produces each number on demand.

Holes are included

This is the behavior that separates keys() from Object.keys(). The array iterator walks every index up to length, whether or not a property exists there.

JavaScript
const sparse = [10, , 30];

console.log([...sparse.keys()]);
console.log(Object.keys(sparse));
console.log(Object.keys(sparse).map(Number));
Text
[ 0, 1, 2 ]
[ '0', '2' ]
[ 0, 2 ]

keys() reports index 1 even though nothing is stored there. Object.keys() lists only existing own properties and returns them as strings. If you iterate indexes to process every slot, keys() is right. If you want to know which slots actually hold values, it is wrong, and Object.keys() or forEach() (which skips holes) is closer.

The same difference appears with a freshly sized array:

JavaScript
const blank = new Array(3);

console.log([...blank.keys()]);
console.log(Object.keys(blank));
Text
[ 0, 1, 2 ]
[]

Three empty slots have three keys by the iterator's count and zero by the object's count. That is occasionally useful: [...new Array(5).keys()] is a well-known way to build [0, 1, 2, 3, 4] without writing a loop.

Building ranges

The hole behavior is why keys() appears in range one-liners.

JavaScript
const range = (n) => [...Array(n).keys()];

console.log(range(4));
console.log(range(4).map((i) => i * 10));
Text
[ 0, 1, 2, 3 ]
[ 0, 10, 20, 30 ]

Array.from({ length: 4 }, (_, i) => i) does the same and reads more directly, so choose by taste. Both create a temporary structure, which is fine for short ranges and a poor fit for millions of items, where a generator function that yields numbers one at a time avoids the allocation.

keys() on typed arrays and array-likes

Typed arrays have their own keys() with the same shape. Array-likes do not, but you can borrow the method because it only needs length.

JavaScript
const bytes = new Uint8Array([7, 8]);
console.log([...bytes.keys()]);

const like = { length: 3, 0: "a", 1: "b", 2: "c" };
console.log([...Array.prototype.keys.call(like)]);
Text
[ 0, 1 ]
[ 0, 1, 2 ]

The second call works because the iterator needs nothing except length. In practice you would convert the array-like with Array.from() first and call keys() on the result.

Comparing keys(), entries() and Object.keys()

Three methods get confused, and the table separates them.

MethodReturnsIndex typeIncludes holes
array.keys()Iterator of indexesNumberYes
array.entries()Iterator of [index, value]NumberYes
Object.keys(array)Array of keysStringNo

If you need both index and value, entries() saves the second lookup:

JavaScript
const rows = ["a", "b"];

for (const [i, row] of rows.entries()) {
  console.log(`${i}:${row}`);
}
Text
0:a
1:b

Use keys() when the index alone matters, such as filling a lookup table or iterating by position against a second array. Use entries() when you need the value as well.

Mutation during iteration

The iterator reads length as it goes, so changing the array while iterating changes the output.

JavaScript
const live = ["a", "b"];

for (const i of live.keys()) {
  if (i === 0) live.push("c");
  console.log(i);
}
Text
0
1
2

The push at index 0 made the array longer, and the iterator then visited the new index. The opposite also holds: removing items shortens the walk. We avoid mutating an array while iterating it, but it is worth knowing that keys() is live and not a snapshot.

Why an iterator and not an array

The design choice behind keys() is worth a paragraph, because it explains the surprises. Returning an iterator means the call costs the same for an array of ten items and an array of ten million: nothing is built until you ask for the next value. A for...of loop that breaks early never pays for the indexes it did not visit. The trade-off is that you cannot index into the result, cannot read its length, and cannot reuse it after one pass. If you try array.keys()[0] you get undefined, not the first index, because an iterator object has no numeric properties. Convert it to an array the moment you need those abilities.

JavaScript
const it = ["a", "b"].keys();

console.log(it[0]);
console.log(typeof it.next);
console.log(Object.prototype.toString.call(it));
Text
undefined
function
[object Array Iterator]

The iterator is its own object type, with a next() method and the standard string tag. It is also iterable itself, so passing it to for...of, spread or Array.from() all work, and each of those drains it.

A failure we hit: assuming a snapshot

A pattern that looks safe and is not: collecting indexes lazily and using them after the array has changed. If you stash the iterator, mutate the array, and consume the iterator later, the indexes reflect the array as it is at consumption time. When you need indexes as they were at one moment, spread them into a real array immediately, and treat that array as the snapshot. This matters in code that removes items from a list while walking it: iterate the snapshot of indexes in reverse, so a removal never shifts an index you have not visited yet.

Where keys() stops being the right tool

If you want the property names of a plain object, keys() does not exist on it: use Object.keys(). If you want to know which slots are populated, the iterator over-reports. And if you only want to loop with an index, forEach((value, index) => ...) or entries() often reads better than going through keys() and indexing back into the array.

Related sibling methods with their own behavior are covered in [the post on indexOf()](/library/javascript-array-indexof). The method is specified at Array.prototype.keys in ECMAScript, and MDN documents it on the Array.prototype.keys page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.