What is the ES6 equivalent of Python 'enumerate' for a sequence?
What is the ES6 way to achieve Python’s enumerate functionality for iterating over a sequence? Learn how JavaScript provides index-value pairs using modern methods like entries() and other iteration techniques.
In Python, the enumerate() function is a handy way to loop over a sequence while getting both the index and the value at the same time. JavaScript (ES6) doesn’t have a built-in function named enumerate, but it provides several ways to achieve the same effect.
Here are the most common approaches in ES6:
Using Array.prototype.entries():
The entries() method returns an iterator of [index, value] pairs.
Example:
const fruits = ["apple", "banana", "cherry"];
for (const [index, value] of fruits.entries()) {
console.log(index, value);
}This is the closest equivalent to Python’s enumerate().
Using forEach():
The forEach() method provides both the element and its index.
Example:
fruits.forEach((value, index) => {
console.log(index, value);
});This is simple and readable, though less flexible if you want to break out early.
Using map() if transformation is needed:
map() can also give access to both the value and index.
Example:
const indexed = fruits.map((value, index) => [index, value]);
console.log(indexed); Best Practice: If you want something very close to Python’s enumerate, for...of with entries() is the most Pythonic approach in ES6. If you’re simply processing items, forEach() is often more straightforward.
In short, while ES6 doesn’t have a direct enumerate() function, entries() and forEach() give you the same power with modern, clean syntax.