Generator Function Syntax
You'll learn how to declare generator functions using the special function* syntax and spot them by their asterisk.
The Special Asterisk
Generator functions look almost like regular functions, but with one critical difference: an asterisk (*) between the function keyword and the function name. This asterisk is the visual signal that tells JavaScript (and other developers) that this function is a generator, not a regular function.
// Regular function
function regularFunction() {
return "I'm normal";
}
// Generator function - note the asterisk!
function* generatorFunction() {
yield "I'm special";
}
Asterisk Placement
JavaScript is flexible about where you place the asterisk. All of these are valid:
function* myGenerator() {} // Most common style
function *myGenerator() {} // Also valid
function * myGenerator() {} // Valid but unusual
Style tip: Most developers prefer function* with the asterisk touching the keyword, making it immediately recognizable.
Why the Asterisk Matters
The asterisk isn't just decoration—it fundamentally changes how the function behaves. When you call a generator function, it doesn't run the code inside immediately like a regular function would. Instead, it returns a special iterator object that you can control step-by-step (which you learned about in previous lessons).
Think of the asterisk as a label on a special vending machine: it looks like a regular function from the outside, but it dispenses results one at a time when you ask for them, rather than giving you everything at once.
Key Takeaway: Generator functions are declared with function* (function keyword + asterisk), which distinguishes them from regular functions and signals their special pause-and-resume behavior.