If I have a Map
in JavaScript, e.g
const myMap = new Map()
myMap.set(0, 'zero')
myMap.set(1, 'one')
Then both of these two seem to be valid to iterate through the key-value pairs (and many other options which I am currently not interested in):
// with .entries()
for (const [key, value] of myMap.entries()) {
//
}
// without
for (const [key, value] of myMap) {
//
}
Is there any edge case where they do not do the same?
Is there any edge case where they do not do the same?
No. The iterator object you get from entries
is exactly the same one provided by the map itself. In fact, someMap[Symbol.iterator]
(the function called when you ask an object for its iterator) is literally the exact same function as someMap.entries
:
const someMap = new Map();
console.log(someMap[Symbol.iterator] === someMap.entries);
In the spec:
Map.prototype.entries
Map.prototype[@@iterator]
(@@iterator
is Symbol.iterator
) — which literally just points to entries