Map[Symbol.iterator]()
The Map[Symbol.iterator]()
method in JavaScript returns an iterator object that yields key-value pairs from a Map
object in insertion order. This method is the default iterator for Map
, meaning a Map
can be iterated using a for...of
loop.
Syntax
map[Symbol.iterator]()
Parameters
This method does not accept any parameters.
Return Value
The Map[Symbol.iterator]()
method returns an iterator object that produces an array of [key, value]
pairs from the Map
in insertion order.
Examples
1. Iterating Over a Map Using for...of
The Symbol.iterator
method allows a Map
to be iterated using a for...of
loop, returning key-value pairs.
const map = new Map([
['name', 'Arjun'],
['age', 25],
['city', 'New York']
]);
for (const entry of map) {
console.log(entry);
}
Output
["name", "Arjun"]
["age", 25]
["city", "New York"]
Each iteration returns an array containing a key-value pair from the Map
.
2. Using next()
to Manually Iterate
You can manually extract key-value pairs using the iterator’s next()
method.
const map = new Map([
['x', 10],
['y', 20]
]);
const iterator = map[Symbol.iterator]();
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().done);
Output
["x", 10]
["y", 20]
true
The done
property of the iterator becomes true
once all elements have been iterated.
3. Spreading a Map Into an Array
The Map[Symbol.iterator]()
method allows a Map
to be spread into an array.
const map = new Map([
['a', 1],
['b', 2]
]);
const array = [...map];
console.log(array);
Output
[["a", 1], ["b", 2]]
The spread operator [...map]
expands the Map
into an array of key-value pairs.