Iterators and for-of loop in JavaScript
Hello everyone, In this article we are going to talk about the Iterators and for ... of loop in Javascript with the help of examples for better understanding.Let's begin
Javascript is a dynamic programming language and offering efficient ways to work with data collections. Iterators are one of the most important structures for iterating the collections to organise the data within them like most of modern programming language.
Iterator is an object in JavaScript allows us to access the elements of all kind of iterable collections like array, set, map in consistant and standardised way. Iterator allow us to traverse the array without the indexes or keys of the elements and organise the data during the iteration as we do with loops and spread operator.
Now lets make some examples about Iterators.
const words = ['the', 'code', 'program'];
const iterator = words[Symbol.iterator]();
console.log(iterator.next()); // { value: 'the', done: false }
console.log(iterator.next()); // { value: 'code', done: false }
console.log(iterator.next()); // { value: 'program', done: false }
console.log(iterator.next()); // { value: undefined, done: true }
As you can see above after we defined our array, we have initialised the iterator with the Symbol.iterator method of iterators. Then we are enabled to use the next() method to get the values of the array with the specifier properties of the value of the element, and the iteration finished with done property.
const range= {
start: 1,
end: 10,
[Symbol.iterator]() {
let current = this.start;
return {
next: () => {
if (current <= this.end) {
return { value: current++, done: false };
}
else return { done: true };
}
};
}
};
for (const num of range) {
console.log(num);
}
As you can see above we have defined a custom iterable and we have initialised our iterable with using our custom one. In our example it will create a number range between given numbers and with for ... of loop we will print this number range.
const myMap = new Map();
myMap.set("name", "Burak");
myMap.set("surname","Tufan");
myMap.set("web","http://thecodeprogram.com");
for (const [key, value] of myMap) {
console.log(`${key}: ${value}`);
}
As you can see above we have traversed our Map and we have printed the key value pairs of our Map with for ... of loop.
That is all
Burak Hamdi TUFAN
Comments