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:
JavaScript
<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.
Javascript
<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.



