How to Use yield in JavaScript: Syntax and Examples
In JavaScript,
yield is used inside a generator function to pause its execution and return a value. When the generator resumes, it continues from where it left off, allowing you to produce a sequence of values over time.Syntax
A generator function is declared with an asterisk * after the function keyword. Inside it, yield pauses the function and sends a value back to the caller. The function resumes when next() is called on the generator object.
- function* name() {}: Declares a generator function.
yield value;: Pauses and returnsvalue.generator.next(): Resumes execution and returns an object with{value, done}.
javascript
function* generatorFunction() { yield 'first'; yield 'second'; return 'done'; }
Example
This example shows a generator that yields three values one by one. Each call to next() resumes the generator and gets the next value until it finishes.
javascript
function* countToThree() { yield 1; yield 2; yield 3; } const counter = countToThree(); console.log(counter.next()); // { value: 1, done: false } console.log(counter.next()); // { value: 2, done: false } console.log(counter.next()); // { value: 3, done: false } console.log(counter.next()); // { value: undefined, done: true }
Output
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }
Common Pitfalls
One common mistake is forgetting to declare the function as a generator with *. Without it, yield causes a syntax error. Another is misunderstanding that yield pauses execution and returns a value, not an object.
Also, calling next() after the generator is done returns {value: undefined, done: true}, so check done to avoid errors.
javascript
/* Wrong: missing * causes syntax error */ // function generator() { // yield 1; // SyntaxError // } /* Right: use * to declare generator */ function* generator() { yield 1; } const gen = generator(); console.log(gen.next()); // { value: 1, done: false }
Output
{ value: 1, done: false }
Quick Reference
- function* name() {}: Declare a generator function.
yield value;: Pause and send value out.generator.next(): Resume generator, get next value.doneistruewhen generator finishes.
Key Takeaways
Use
function* to declare a generator function that can use yield.yield pauses the function and returns a value each time next() is called.Always check the
done property to know when the generator has finished.Forgetting the
* in the function declaration causes syntax errors with yield.Generators let you produce values one at a time, useful for sequences and lazy computations.