JavaScript Generators & Yield Keyword Explained

Day 38/50 – JavaScript Interview Question? Question: What are JavaScript Generators and the yield keyword? Simple Answer: Generators are special functions that can pause and resume execution. They're defined with function* and use yield to return values one at a time. Each call to .next() resumes execution until the next yield or return statement. 🧠 Why it matters in real projects: Generators enable lazy evaluation (processing large datasets without loading everything into memory), implementing custom iterators, managing async flow (Redux-Saga uses generators), and creating infinite sequences efficiently. 💡 One common mistake: Forgetting that calling a generator function doesn't execute it immediately—it returns an iterator object. You must call .next() to start execution. Also, not understanding that yield can both send and receive values. 📌 Bonus: // Basic generator function* numberGenerator() { console.log('Start'); yield 1; console.log('After 1'); yield 2; console.log('After 2'); yield 3; return 'Done'; } const gen = numberGenerator(); // Doesn't execute yet! console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: 'Done', done: true } // Practical use cases: // 1. Infinite sequences function* fibonacci() { let [a, b] = [0, 1]; while (true) { yield a; [a, b] = [b, a + b]; } } const fib = fibonacci(); console.log(fib.next().value); // 0 console.log(fib.next().value); // 1 console.log(fib.next().value); // 1 console.log(fib.next().value); // 2 // 2. Lazy evaluation (memory efficient) function* readLargeFile(file) { for (let line of file) { yield processLine(line); // Process one line at a time } } // 3. Custom iterators function* range(start, end) { for (let i = start; i <= end; i++) { yield i; } } for (let num of range(1, 5)) { console.log(num); // 1, 2, 3, 4, 5 } // 4. Two-way communication function* twoWay() { const a = yield 'First'; console.log('Received:', a); const b = yield 'Second'; console.log('Received:', b); } const gen2 = twoWay(); gen2.next(); // { value: 'First', done: false } gen2.next('Hello'); // Logs: Received: Hello gen2.next('World'); // Logs: Received: World #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Generators #ES6 #WebDev #InterviewPrep #AdvancedJS

To view or add a comment, sign in

Explore content categories