Skip to content
Related Articles

Related Articles

Improve Article

JavaScript Map.prototype[@@iterator]() Method

  • Last Updated : 18 May, 2021

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']



My Personal Notes arrow_drop_up
Recommended Articles
Page :