JavaScript | Iterator

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

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>
<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
0 1 2 3 4
javascript-functions
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.