How to Use Entries and Keys in Array in JavaScript
In JavaScript, use
array.entries() to get an iterator of [index, value] pairs, and array.keys() to get an iterator of indexes only. These methods help you loop through arrays when you need both positions and elements or just the positions.Syntax
array.entries() returns an iterator with [index, value] pairs for each element in the array.
array.keys() returns an iterator with the indexes (keys) of the array elements.
You can use these iterators with for...of loops to access array data.
javascript
const array = ['a', 'b', 'c']; const entriesIterator = array.entries(); const keysIterator = array.keys();
Example
This example shows how to use entries() to get index and value pairs, and keys() to get only indexes from an array.
javascript
const fruits = ['apple', 'banana', 'cherry']; console.log('Using entries():'); for (const [index, fruit] of fruits.entries()) { console.log(index, fruit); } console.log('Using keys():'); for (const index of fruits.keys()) { console.log(index); }
Output
Using entries():
0 apple
1 banana
2 cherry
Using keys():
0
1
2
Common Pitfalls
One common mistake is trying to use entries() or keys() directly as arrays without iterating. These methods return iterators, not arrays.
Also, using forEach with entries() won't work directly because entries() returns an iterator, not an array.
javascript
const arr = ['x', 'y', 'z']; // Wrong: trying to use entries() as an array // console.log(arr.entries()[0]); // Error: entries() is not an array // Correct: use for...of to iterate for (const [i, val] of arr.entries()) { console.log(i, val); }
Output
0 x
1 y
2 z
Quick Reference
| Method | Description | Returns |
|---|---|---|
| array.entries() | Iterator of [index, value] pairs | Iterator object |
| array.keys() | Iterator of indexes (keys) only | Iterator object |
| array.values() | Iterator of values only | Iterator object |
Key Takeaways
Use
array.entries() to get both indexes and values when looping.Use
array.keys() to get only the indexes of array elements.Both methods return iterators, so use
for...of to loop through them.Do not treat
entries() or keys() as arrays directly.These methods help write clear loops when you need positions or pairs from arrays.