Understanding Iterators and Generators in JavaScript

Today I Learned: Iterators & Generators in JavaScript One of the most interesting parts of modern JavaScript is how it handles iteration, and today I finally understood how Iterators and Generators work under the hood! 🧠 1. Iterators An iterator is simply an object that defines how to step through a sequence, one value at a time. It follows the pattern: const iterator = [10, 20, 30][Symbol.iterator](); console.log(iterator.next()); // { value: 10, done: false } console.log(iterator.next()); // { value: 20, done: false } Each call to .next() gives you the next value until done: true. ⚙️ Generators A generator function (defined with function*) automatically creates an iterator for you. function* greet() { yield "Hi"; yield "Hello"; yield "Hey"; } const it = greet(); console.log(it.next().value); // Hi console.log(it.next().value); // Hello What’s cool is that you can pause and resume function execution! 🔥 💡 Key Takeaway: Iterators let you take control of how data is accessed. Generators make it easier to build your own iterators — letting you write asynchronous, lazy, and powerful code structures. Every day, I’m realising how deep JavaScript really is — and how beautiful its design becomes when you understand what’s happening under the hood. #JavaScript #WebDevelopment #LearningInPublic #BackendDevelopment #ES6

To view or add a comment, sign in

Explore content categories