Posted by
Jayesh Shinde
on November 21, 2019 ·
6 mins read
One of the most powerful feature of ECMA6 is Generator Functions, which is the most favourite topics for interviewers. Generator functions are nothing but, can be exited and later re-entered, where their context will be saved across re-entrances. ie. Can be stopped in Midway and continued from where it is Stopped.
Some of the tricky question asked:
What is the generator function return type?
Can generator function support “return” apart from “yield”?
How we can pass arguments or new value to generator function?
Generators are construct-able?
How the generator function works?
Below section of the post describe all the answers.
Generator object, which confirms to Iterable and Iterator protocol. Used in conjunction with Promises they resolve the problem with Callback Hell and Inversion of Control.
Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.
When the iterator’s next() method is called, the generator function’s body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.
The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean.
{ value: Any, done: false | true }
Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where execution was paused with the argument from next().
A return statement in a generator, when executed, will make the generator finish ({ value: Any, done: true }).
If an error thrown inside the generator will make the generator finished – unless caught within the generator’s body.
When a generator is finished, subsequent next calls will not execute any of that generator’s code, they will just return an object of this form: {value: undefined, done: true}.
Interview Tips
Write a function which will print all the letters of a given sentences sequentially, “United We Stand”.
Some of the True Statements about Generators:
Generators can be used to create infinite data-series, that never ends.
Generators can be used as observers which receives the new value using next(val)
Generators are Memory Efficient as they generate the value which is needed.
Generator Objects are one time access only. Once you exhausted all value, you can not iterate over.
Generators are defined in an expressions.
Generators are not constructable.
Generators can be used as Computed Property or Object Method.
Generators support “return” statement post which it’s executions gets stopped.
Generators are commonly used in Redux-Saga based middleware, which construct most of the Actions part.