A normal function runs from start to finish in one go. A generator function can pause in the middle, hand a value back, and resume later exactly where it stopped. That makes it perfect for producing values one at a time β without building a giant array first.
You write a generator with function* and pause it with yield :
function * countUp ( ) { yield 1 ; yield 2 ; yield 3 ; }
const counter = countUp ( ) ; 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 }
Enter fullscreen mode
Exit fullscreen mode
Each call to next() runs the function until the next yield , then pauses again. The returned object tells you the value and whether the generator is finished.
Generators are most useful when the sequence is long or infinite.β¦