Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript | Iterator

  • Last Updated : 29 Jan, 2020

It’s an object or pattern that allows us to traverse over a list or collection. Iterators define the sequences and implement the iterator protocol that returns an object by using a next() method that contains the value and done. The value contains the next value of iterator sequence and the done is the boolean value true or false if the last value of the sequence has been consumed then it’s true else false. We can check if any entity is by default iterable or not

We can check its prototype and can see if it is having a method Symbol(Symbol.iterator) or not. In Array.prototype you will find Symbol(Symbol.iterator): ƒ values() method. Array is by default iterable. Also, String, Map & Set are built-in iterables because their prototype objects all have a Symbol.iterator() method.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

  • Program:




    <script>
      
    const array = ['a', 'b', 'c'];
      
    const it = array[Symbol.iterator]();
      
    // and on this iterator method we have ‘next’ method
      
    document.write(JSON.stringify(it.next()));
    //{ value: "a", done: false }
      
    document.write(JSON.stringify(it.next()));
    //{ value: "b", done: false }
      
    document.write(JSON.stringify(it.next()));
    //{ value: "c", done: false }
      
    document.write(JSON.stringify(it.next()));
    /* Actual it.next() will be { value: undefined, 
    done: true } but here you will get
    {done: true} output because of JSON.stringify 
    as it omits undefined values*/
      
      
    </script>                    
  • Output:
    {"value":"a","done":false}{"value":"b","done":false}
    {"value":"c","done":false}{"done":true}

Using for.of loop, we can iterate over any entity (for eg: object) which follows iterable protocol. The for.of loop is going to pull out the value that gets a return by calling the next() method each time.

  • Program:




    <script>
      
    const array = ['a', 'b', 'c'];
      
    const it = array[Symbol.iterator]();
      
    for (let value of it) {document.write(value)}
      
    </script>                    
  • Output:
    abc

Iterable protocol: The object must define a method with ‘Symbol.iterator’ the key which returns an object which itself follows iterator protocol. The object must define ‘next’ method which returns an object having two properties ‘value’ and ‘done’

  • Syntax:
    {value: 'item value', done: boolean}
  • Error scenario:
    var newIt = arr[Symbol.iterator]
    
    newIt()
    
    //Because it does not properly bind
    Uncaught TypeError: Cannot convert undefined or null to object 
    //How we can fix this 
    //var newIt = arr[Symbol.iterator].bind(arr); 
    
    newIt()
    Array Iterator { }
    

Create our own iterable object:




  • <script>
    var iterable = {
      i: 0,
      [Symbol.iterator]() {
        var that = this;
        return {
          next() {
            if (that.i < 5) {
              return { value: that.i++, done: false }
            } else {
              return { value: undefined, done: true }
            }
          }
        }
      }
    }
      
    for(let value of iterable){document.write(value)}
    </script>
  • Output:
    0 1 2 3 4



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!