DEV Community

Cover image for Day 47 of #100DaysOfCode:Review ES6 Generators & Iterators
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Edited on

2

Day 47 of #100DaysOfCode:Review ES6 Generators & Iterators

Introduction

Generators is a new feature from ES6 which can help us to maintain the internal state (pause and resume)

The Iterator Protocol

  • The iterator protocol means a process for defining how an object will iterate.This is done through implementing the .next() method.
const list = [0, 1, 2, 3, 4, 5];
const arrayIterator = list[Symbol.iterator]();

console.log(arrayIterator.next());
console.log(arrayIterator.next());
console.log(arrayIterator.next());
/*
will print:
Object {value: 0, done: false}
Object {value: 1, done: false}
Object {value: 2, done: false}
*/
Enter fullscreen mode Exit fullscreen mode
  • value: represent the next value in the sequence
  • done: represent if the iterator is done ging through the sequence

Pausable Functions

  • When a generator is invoked, it doesn't actually run any of the code inside the function. Instead, it creates and returns an iterator.
  • The function will be transformed to a pausable function if we put asterisk after the function keyword.
  • yield is the keyword that causes the generator to pause
  • The state machine(Generators) will transform the state: initial state -> resume -> pause (state 1) -> resume -> pause (state 2) -> resume -> .... -> end (state N)

Alt Text

Sending data into/out of a Generator

  • yield is used to send data outside the generator
  • .next() method is used to send data inside the generator
function* gen3() {
    for (let i = 0; i< 10; i++) {
        let value = yield i
        console.log(`sending data into generator: ${value}`)
    }
}


var g = gen3()
console.log(`sending data out of generator: ${g.next().value}`)
console.log(`sending data out of generator: ${g.next(10).value}`)
console.log(`sending data out of generator: ${g.next(20).value}`)
/*
will print:
sending data out of generator: 0
sending data into generator: 10
sending data out of generator: 1
sending data into generator: 20
sending data out of generator: 2
*/
Enter fullscreen mode Exit fullscreen mode

Articles

There are some of my articles and released projects. Feel free to check if you like!

References

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay