Generators are a function that is used for lazy execution. it is used to execute suspended and resumed at a later point.
Generators have two methods
Yield method – This method is called in a function to halt the execution of the function at the specific line where the yield method is called.
Next method – This method is called from the main application to resume the execution of a function that has a yield method. The execution of the function will continue until the next yield method or till the end of the method.
function* addNumber(x) {
yield x + 1; //value of x is 6 but halted program
var y = 2;
return x + y;
}
var gen = addNumber(5);
console.log(gen.next().value); //6
console.log(gen.next().value); //7
What is Generators – Interview Questions
Q 1: What is a generator function?
Ans: A function that can pause and resume execution.
Q 2: Syntax of generator function?
Ans: function* name(){}.
Q 3: Which keyword is used to pause?
Ans: yield.
Q 4: How to resume generator?
Ans: Using .next().
Q 5: Use case of generators?
Ans: Handling asynchronous operations.
What is Generators – Objective Questions (MCQs)
Q1. Generator functions are declared using ______.
Q2. Which keyword pauses execution in generators?
Q3. Calling a generator function returns a ______.
Q4. Which method resumes generator execution?
Q5. Generators are useful for ______.