The entries() method is a powerful built-in tool in JavaScript used to create an Array Iterator object. This iterator contains the key/value pairs for each index in the array, where the “key” is the numeric index ($0, 1, 2, \dots$) and the “value” is the element stored at that index.
It is particularly useful when you need to loop through an array but require access to both the element and its position simultaneously, providing a cleaner alternative to traditional for loops or forEach callbacks.
1. Syntax and Return Value
The method does not accept any parameters and returns an iterable object.
array.entries();
Return Value
An Array Iterator object. This object is not an array itself; it is a pointer that moves through the array’s elements. Each “step” of the iterator yields an array in the format [index, element].
2. Iteration with for...of
The most common and readable way to consume the entries() iterator is through a for...of loop combined with array destructuring.
const fruits = ["Apple", "Banana", "Cherry"];
const iterator = fruits.entries();
for (const [index, element] of iterator) {
console.log(`Index: ${index}, Value: ${element}`);
}
/* Output:
Index: 0, Value: Apple
Index: 1, Value: Banana
Index: 2, Value: Cherry
*/
3. Manual Iteration with .next()
Because the return value is a standard iterator, you can manually traverse it using the .next() method. This is useful for complex logic where you might not want to process the entire array at once.
const sequence = ['a', 'b'];
const entryIterator = sequence.entries();
console.log(entryIterator.next().value); // [0, 'a']
console.log(entryIterator.next().value); // [1, 'b']
console.log(entryIterator.next().done); // true
4. Handling Sparse Arrays
A “sparse” array is one where some indices are empty (e.g., [1, , 3]). Unlike older iteration methods like forEach(), which skip empty slots, the entries() method visits every index, returning undefined for missing values.
const sparseArray = ["a", , "c"];
for (const [i, val] of sparseArray.entries()) {
console.log(i, val);
}
// Output:
// 0 "a"
// 1 undefined <-- entries() visits the empty slot
// 2 "c"
5. Practical Use Case: Data Transformation
The entries() method is ideal when you need to transform an array into an object where the index serves as a specific key or when building mapped structures.
const alphabet = ['a', 'b', 'c'];
// Convert array to a Map for O(1) lookups by index
const alphaMap = new Map(alphabet.entries());
console.log(alphaMap.get(1)); // "b"
