Javascript-Iterators
Javascript-Iterators 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 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.
In Array.prototype you will find Symbol(Symbol.iterator): ƒ values() method. The array is by default iterable. String, Map and set are built-in Iterators because their prototype objects all have a Symbol.iterator() method.
Example:
<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 which follows iterable protocol. The for.of loop is going to pull out the values that get a return by calling the next() method each time.
Example:
<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 iterator object must provide a method with ‘Symbol.iterator’ the key which returns an object which itself follows iterator protocol. The iterator object must define the ‘next’ method which returns an object having two properties ‘value’ and ‘done’.
Syntax:
{value: 'item value', done: boolean}
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