Instruction: Define what Generators are in JavaScript and demonstrate their usage with an example.
Context: This question aims to assess the candidate's understanding of Generators in JavaScript, their syntax, and how they can be used to control function execution.
Official answer available
Preview the opening of the answer, then unlock the full walkthrough.
Generators are declared with a function* syntax, and they generate a sequence of values using the yield keyword. Unlike regular functions that run to completion when called, a generator function returns a Generator object when it's invoked. This object adheres to both the iterable protocol and the iterator protocol, meaning it can be used in a for...of loop and it has a next() method, which resumes the function execution from the last yield point.
Here's a straightforward example to demonstrate their usage:...
easy
medium
medium
hard
hard
hard