in JavaScript by
Q:
What are generator functions?

1 Answer

0 votes
by

Introduced in ES6 version, generator functions are a special class of functions.

They can be stopped midway and then continue from where it had stopped.

Generator functions are declared with the function* keyword instead of the normal function keyword:

function* genFunc(){

  // Perform operation

}

In normal functions, we use the return keyword to return a value and as soon as the return statement gets executed, the function execution stops:

function normalFunc(){

  return 22;

  console.log(2); // This line of code does not get executed

}

In the case of generator functions, when called, they do not execute the code, instead they return a generator object . This generator object handles the execution.

function* genFunc(){

  yield 3;

  yield 4;

}

genFunc(); // Returns Object [Generator] {}

The generator object consists of a method called next() , this method when called, executes the code until the nearest yield statement, and returns the yield value.

For example if we run the next() method on the above code:

genFunc().next(); // Returns {value: 3, done:false}

As one can see the next method returns an object consisting of value and done properties.

Value property represents the yielded value.

Done property tells us whether the function code is finished or not. (Returns true if finished)

Generator functions are used to return iterators. Let’s see an example where an iterator is returned:

function* iteratorFunc() {

  let count = 0;

  for (let i = 0; i < 2; i++) {

      count++;

      yield i;

  }

  return count;

}

let iterator = iteratorFunc();

console.log(iterator.next()); // {value:0,done:false}

console.log(iterator.next()); // {value:1,done:false}

console.log(iterator.next()); // {value:2,done:true}

As you can see in the code above, the last line returns done:true , since the code reaches the return statement.

Click here to read more about JavaScript
Click here to read more about Insurance

Related questions

0 votes
asked Feb 6, 2020 in JavaScript by rajeshsharma
+1 vote
0 votes
asked Oct 19, 2019 in JavaScript by SakshiSharma
0 votes
0 votes
asked Dec 19, 2019 in Python by sharadyadav1986
0 votes
asked Jan 13, 2020 in Bootstrap by astao231
+1 vote
asked Sep 12, 2020 in QuickTest Professional (QTP) by JackTerrance
...