Iterators and for-of loop in JavaScript

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.

Iterator has two methods in Javascript:
  • next(): Returns an object with two properties ( value and done ) to represent the element and is to specify the last element.
  • Symbol.iterator: An iterable object like an array or a custom collection implementation that we can implement. It is a transforming the iterable to our own custom implementation.

Now lets make some examples about Iterators.

Below you can see the usage of iterators with normal arrays

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.


With Symbol.iterator method, we can create our custom iterables and we can process data within our own custom logic.

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.


Now lets make some examples with for ... of loop and iterate a Map.

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


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...