Generators

Bashar Ayyash
2 min readAug 29, 2015

--

This post is a part of Starter to ES6

They are new ES6 feature and marked with asterisk (*) which are functions that can pause and resume later. Generators functions return iterable object where you can use next() method.

function* genFun(){

console.log(‘Start’);
yield;
console.log(‘Finish’);
}

let gFun = genFun();
gFun.next();//Start
gFun.next();//Finish

The generator at beginning of execution is suspended until you call next() method which gives the result before yield and return iterable object {value: …, done: false/true} indicate if the generator done or not.

3.1.2 To create generators there are four ways to do that.

  1. Declaration: function* gFun() { … }
  2. Expression: const gFun = function* () { … }
  3. Definition in an object:
    let obj = { * genMethod() { … } }; let x = obj.genMethod();
  4. Definition in a class:
    class MyClass { * genMethod() { … };
    }
    let classInst = new MyClass();
    let genObj = classInst.genMethod();

3.2. You can use generators in different ways as below:

function* genFun(){
console.log(‘Start’);
yield;
console.log(‘Finish’);
}

  • for-of:
    for(let x of genFun()){ console.log(x);
    }
  • Using ES6 spread operator ( … yes as you can see three dots ;)
    let arr = […genFun()];//[‘Start’, ‘Finish’];
    The spread operator convert the iterated sequence element to array element
  • Destructuring
    let [x, y] = genFun();
    console.logo(x);// Start
    console.log(y);// Finish
  • Generators with explicit return
    function* genFun2(){ console.log(‘Start’); yield; console.log(‘Finish’); return ‘End’;
    }
    let genObj = genFun();
    genObj.next();//{value:’Start’, done: false}
    genObj.next();//{value:’Finish’, done: false}
    genObj.next();//{value:’End’, done: true}
  • Most constructs that work with iterables ignore the value inside the last done object
    for(let x of genFun2()){ console.log(x);
    }
    //Start
    //Finish
  • Recursive yield ( *yield ) used to place generator inside another generator
    function* genFun(){ yield ‘Start’; yield ‘Finish’;
    }
    function* genFun2(){ yield ‘End’; yield* genFun(); yield ‘Close’;
    }
  • let arr = […genFun2()]; //arr = [‘Start’, ‘End’, ‘Close’, ‘Finish’];

This post is a part of Starter to ES6

--

--

Bashar Ayyash

Front End Developer, I’m confident that Vue.js is as powerful as React, but way more flexible and a lot easier to learn