What are JavaScript Generators and how do they work?

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.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

A generator function, written with function*, returns a generator object. Calling the function does not immediately execute its body. Calling next resumes it until a yield, return or exception; next returns an object with value and done.

function* steps() { yield 'first'; yield 'second'; return 'finished'; } const iterator = steps(); console.log(iterator.next()); // { value: 'first', done: false } console.log(iterator.next()); // { value: 'second', done: false } console.log(iterator.next()); // {...

Related Questions