Javascript Iterator is 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 is done. The value contains the next value of the 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. The array is by default iterable. Also, String, Map & Set are built-in iterables because their prototype objects all have a Symbol.iterator() method.
Example: This example uses the symbol.iterator approach to iterate over the array.
javascript
<script> const array = [ 'a' , 'b' , 'c' ]; const it = array[Symbol.iterator](); // and on this iterator method we have ‘next’ method console.log(JSON.stringify(it.next())); //{ value: "a", done: false } console.log(JSON.stringify(it.next())); //{ value: "b", done: false } console.log(JSON.stringify(it.next())); //{ value: "c", done: false } console.log(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: an 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.
Example: This example uses a for..of loop to iterate over the array.
javascript
<script> const array = [ 'a' , 'b' , 'c' ]; const it = array[Symbol.iterator]() for (let value of it) {console.log(value)} </script> |
Output:
a b c
Iterable protocol: The object must define a method with ‘Symbol.iterator’ the key which returns an object that itself follows iterator protocol. The object must define the ‘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:
javascript
<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){console.log(value)} </script> |
Output:
0 1 2 3 4