Learn Js with Ut

Iterable or Iterator in js

July 01, 2020

Iterable 😕

In js iterable is an protocol that allows us to define or customize the iteration of an object. Allow us to iterate any object via for..of, {...spread} etc.

There are some built-in iterables in JS like Array,String,Map,Set etc. These built-in iterable are looped with for..of loop.

We can also create our own iterable object by using constant Symbol.iterator as a method inside the iterable Object.

Let’s create our own Iterable:

//first we create a simple object.
let iterableObj = {
  from: 1,
  to: 3,
}

// Now to make it iterable we have to define [Symbol.iterator]() as a method in iterableObj.
iterableObj[Symbol.iterator] = function () {
  // This function will return an iterator object{}
  //Over which for...of loop will start its iteration.
  return {
    // This is iterator object which is used by for..of loop.
    // this iterator object have next() method i.e call by for..of loop to get
    // the next value
    current: this.from,
    last: this.to,
    //whenever for..of wants new value, it calls next()
    next() {
      if (this.current <= this.last) {
        return { done: false, value: this.current++ };
      } else {
        return { done: true };
      }
    },
  };
}

// now see result...
for (let key of iteratorObj) {
  console.log(key) // 1,2,3
}
😵😵

The above example looks like messy😵. Let me explain

  • First we initialize an obj that we want to make it like iterable.
  • second we define a method inside obj i.e [Symbol.iterator] i.e call by for..of loop when it start iteration.
  • That return an iterator object on which for..of loops work. Which contains next() method.
  • whenever for..of loop want next value then it calls the next() method.
  • next() function return an object like {done:Boolean,value:any} must be in this form.

    • If done=true the iteration is finished otherwise value is the next value and done=false.

That’s it.

Iterator

Iterator is an object i.e return by the [Symbol.iterator] function with next() method.

Let’s see in more simple way

let iteratorObj = {
    from:1,
    to:3,
    [Symbol.iterator](){
    return { //Iterator object with next() method
        current:this.from,
        last:this.to,
        next(){
          if(this.current <= this.last){
              return {done:false,value:this.current++};
          }else{
              return {done:true};
          }
        },
      };
    }

};

for(let val of iteratorObj){
   console.log(val); //1,2,3
}

Now jump on some iteration protocols example

A String is an built-in iterable object in js.

For Example:

let str = "hi"; // a simple string

//Now add some more engineering

// String have its own Symbol.iterator function
let iterator = str[Symbol.iterator]();
// here iterator store iterator Obj i.e return by the [Symbol.iterator]()
console.log(iterator.next()); // {value:"h",done:false}
console.log(iterator.next()); // {value:"i",done:false}
console.log(iterator.next()); // {value:undefined,done:true}

//Some construct also work on iterator protocol
console.log([...str]); //  ["h", "i"]
const [firstLetter,secLetter] = [...str];
console.log(firstLetter,secLetter); // "h" "i"

Iterable Example:

// Map is built in iterable
let maps = new Map([[3,"chainSmokers"],[5,"Dj snake"],[1,"Gryffin"]]);

console.log(maps.get(3)); // chainSmokers
let sets = new Set("123");
console.log(sets.has('2')); //true

Summary

  • Objects that can be used in for..of loop,[...spread] etc are called iterable.
  • Iterable must have a method named Symbol.iterator.

    • The return value of Symbol.iterator method is called iterator object.
    • An iterator obj must have next() method that returns an object {done:Boolean,value:any}.
  • The Symbole.iterator is automatically call by the for..of loop.But we can also call it directly.
  • There are some built-in iterables like Array,String,Map,Set,weakMap,PromisAll([iterable]) etc.They also implement Symbol.iterator.
  • There are some statement or construct like for..of,spread operator,destructuring,generatorsetc. That expect iterable for iteration.


Please subscribe our news letter

If you like what you just read. Please subscribe to our newsletter. So new content will be delivered to your inbox :)

Hii this is Utkarsh Srivastava. I live in India. I
Coding, Learning New Tech, and Playing PC Games. You can find me on
© 2020, Built with