0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Generator Function in JavaScript: Syntax and Examples

In JavaScript, you create a generator function by adding an asterisk * after the function keyword and using the yield keyword inside it to pause and resume execution. Calling this function returns a generator object that you can iterate over to get values one at a time.
📐

Syntax

A generator function is declared with an asterisk * after the function keyword. Inside the function, yield is used to pause the function and send a value back to the caller. The function returns a generator object when called.

  • function*: Declares a generator function.
  • yield: Pauses the function and returns a value.
  • generator object: Returned when calling the generator function, used to get values.
javascript
function* generatorName() {
  yield value1;
  yield value2;
  // more yields
}
💻

Example

This example shows a generator function that yields three numbers one by one. We use the next() method to get each value from the generator.

javascript
function* countUpToThree() {
  yield 1;
  yield 2;
  yield 3;
}

const counter = countUpToThree();
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3
console.log(counter.next().done);  // true (no more values)
Output
1 2 3 true
⚠️

Common Pitfalls

Common mistakes include forgetting the asterisk * after function, which makes it a normal function instead of a generator. Another mistake is not using yield inside the function, so it behaves like a regular function. Also, calling the generator function does not run the code immediately; you must use next() to start execution.

javascript
/* Wrong: Missing asterisk, so no generator */
function wrongGenerator() {
  // yield 1; // SyntaxError: Unexpected identifier
}

/* Correct: With asterisk and yield */
function* rightGenerator() {
  yield 1;
}
📊

Quick Reference

ConceptDescription
function*Declares a generator function
yieldPauses and returns a value from the generator
generator.next()Gets the next value from the generator
generator.doneTrue when generator has no more values

Key Takeaways

Use function* to declare a generator function in JavaScript.
Inside the generator, use yield to pause and return values one at a time.
Calling a generator function returns a generator object, not the final result.
Use next() on the generator object to get each yielded value.
Remember to include the asterisk * or you will get syntax errors.