Welcome Guest! (App Version 3.1)

websitnero logo name

Generators

What are Generator Functions?

Generator is a function that can stop midway and then continue again later from where it stopped. This special function comes as part of ES6. An anology of it can be put like putting a bookmark in a book. While reading you can go to do other things and later just begin again from where you put the bookmark.

Normal Function V Generator

A normal function in JavaScript follows Run to Completion model meaning it cannot be stopped in between. It starts and then ends without stopping anywhere in between. Look at the following example:

function alpha(){
  console.log(10);
  console.log(20);
  console.log(30);
}
alpha();

Output:

10
20
30

If you try to run the function again, it will again run from top and then end after going through the last line of code inside it OR either it encounters return keyword. But, it cannot stop in between and when run again, will again start fresh from the 1st line inside its code.

Generators can do something the normal functions cannot do, ie, it can stop somewhere in between and later start running from this bookmark point only.

function * beta(){
  console.log(10);
  yield;
  console.log(20);
  yield;
  console.log(30);
  yield;
  console.log(40);
}

var a = beta();
console.log(a.next()); //Output: 10
console.log(a.next()); //Output: 20
console.log(a.next()); //Output: 30
WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.