Let's Understand Iterators & Generators.

Let's Understand Iterators & Generators.

Let's just understand about iterators and generators in javascript. I will try to explain about:

  • What are iterators?

  • How Iterators work?

  • What are Generators?

  • How Generators Works?

  • Advantages of Generators

Let's pick one by one.

What are iterators?

Javascript introduced the iterator in ES6 for traversing the data. We have two concepts around the iterators.

  1. An iterable is a data structure that wants to make its elements accessible to the public. It does so by implementing a method whose key is Symbol.iterator. That method is a factory for iterators.

  2. An iterator is a pointer for traversing the elements of a data structure.

What values are Iterable in Javascript?

  • Array

  • Maps

  • Sets

  • Strings

How Iterators work?

An iterator is an object that implements the Iterator Policy which uses the next() to yield the next value. It has two properties.

  1. value: The next value in the iteration sequence.

  2. done: This is true if there is no value left to iterate otherwise it equals false.

You can look for Iterator example with help of code:

<script>

const array = ['a', 'b', 'c'];

const it = array[Symbol.iterator]();

// and on this iterator method we have the ‘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>

What are Generators?

Generator functions allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the function* syntax.

The function can be called as many times as desired and returns a new Generator each time. Each Generator may only be iterated once.

How Generators Works?

Generator functions do not initially execute their code. Instead, they return a special type of iterator, called a Generator. When a value is consumed by calling the generator's next method, the Generator function executes until it encounters the yield keyword.

function* generatorFunc(){
  yield "1";
  console.log("Hi");
  yield "2";
  console.log("How are you?");
  console.log("I am fine!");
  yield "3"
}
let gen = generatorFunc()

console.log(gen.next()); 
// {"value":"1","done":false}
console.log(gen.next()); 
// Hi
// {"value":"2","done":false}
console.log(gen.next()); 
// How are you?
// I am fine!
// {"value":"3","done":false}

Advantages of Generators

  • Lazy Evaluation: This is an evaluation model which delays the evaluation of an expression until its value is needed. That is, if the value is not needed, it will not exist. It is calculated on demand.

  • Memory Efficient: A direct consequence of Lazy Evaluation is that generators are memory efficient. The only values generated are those that are needed. With normal functions, all the values must be pre-generated and kept around in case they need to be used later. However, with generators, computation is deferred.

Conclusion

Iterator and generator are so underappreciated concepts of javascript that still need to use it to their true potentials. We have some great use cases of them like:

  • Generating the infinite loop.
  • Extracting the username from the given string. (Will explain in another blog)
  • For loop which can be paused and use later.
  • Creating iterables, so they can be used for "For of Loop" from non-iterable objects using [Symbol.Iterator]

Thanks for Reading!!