
JavaScript Generators and Iterators: A Practical Guide
Generators are one of JavaScript's most underused features. Once you understand them, you'll find uses everywhere. The Core Concept A generator function can pause and resume. It yields values one at a time. function * counter () { let n = 0 ; while ( true ) { yield n ++ ; // Pause here, return n, resume on next call } } const gen = counter (); gen . next (); // { value: 0, done: false } gen . next (); // { value: 1, done: false } gen . next (); // { value: 2, done: false } // Infinite sequence, no memory issues The * makes it a generator. yield is the pause point. Infinite Sequences function * fibonacci () { let [ a , b ] = [ 0 , 1 ]; while ( true ) { yield a ; [ a , b ] = [ b , a + b ]; } } // Take first 10 Fibonacci numbers function take ( gen , n ) { const result = []; for ( const value of gen ) { result . push ( value ); if ( result . length === n ) break ; } return result ; } take ( fibonacci (), 10 ); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] Lazy Evaluation Process huge datasets with
Continue reading on Dev.to Webdev
Opens in a new tab



