JavaScript Map.prototype[@@iterator]() Method
Map[@@iterator]( ) method is used to make Map iterable. Map[@@iterator]( ) method returns iterator object which iterates over all code points of Map. Map[@@iterator]( ) is built-in property of Map.
We can use this method by creating Map iterator. We can make Map iterator by calling the @@iterator property. In place of @@iterator, we can use Symbol.iterator constant.
Syntax:
const iter = Map[ Symbol.iterator]();
Parameters: This property does not accept any parameters. Return Value: It returns an iterator to iterating code point of iterator objects.
Example:
<script>
const m = new Map();
m.set(0, "a")
m.set(2, "b")
m.set(3, "c")
const iterator = m[Symbol.iterator]();
let itr = iterator.next()
for (let i = 0; i < script m.size; i++) {
console.log(itr.value, itr.done)
itr = iterator.next()
}
</script>
Output:
[0 : 'a'] false [1 : 'b'] false [2 : 'c'] false
Example: We can use Map.prototype[@@iterator] method with assign Map to the iterator. We can use for loop to iterate over the code point of Map. The for-of loop uses an iterator to iterate over values of Map.
<script>
const m = new Map();
m.set(0, "a")
m.set(2, "b")
m.set(3, "c")
const iterator = m[Symbol.iterator]();
let itr = iterator.next()
for (let i = 0; i < m.size; i++) {
console.log(itr.value)
itr = iterator.next()
}
console.log("iterating with for-of loop : ")
for (let i of m) {
console.log(i)
}
</script>
Output:
[0 : 'a'] [1 : 'b'] [2 : 'c'] iterating with for-of loop : [0 : 'a'] [1 : 'b'] [2 : 'c']
Supported Browsers:
- Chrome 38 and above
- Edge 12 and above
- Firefox 13 and above
- Internet Explorer 11 and above
- Opera 25 and above
- Safari 8 and above
We have a complete list of Javascript Map methods, to check those please go through this JavaScript MapComplete Reference article.