codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🌐

JavaScript

55 / 65 topics
50JavaScript Template Literals51JavaScript Destructuring52JavaScript Spread & Rest Operators53JavaScript Default Parameters54JavaScript Modules (import/export)55JavaScript Iterators and Generators56JavaScript Proxies
Tutorials/JavaScript/JavaScript Iterators and Generators
🌐JavaScript

JavaScript Iterators and Generators

Updated 2026-05-12
35 min read

JavaScript Iterators and Generators

In the modern JavaScript landscape, iterators and generators are powerful tools that allow you to work with sequences of values in a more controlled and flexible manner. Whether you're dealing with complex data structures or managing asynchronous operations, understanding these concepts is crucial for writing efficient and maintainable code.

Introduction

JavaScript iterators provide a way to traverse through the elements of an iterable object (like arrays, strings, maps, etc.) one by one. Generators, on the other hand, are functions that can be paused and resumed, making them ideal for handling asynchronous operations or generating sequences of values over time.

In this tutorial, you'll learn how to create custom iterable objects and use generator functions in JavaScript. These features will help you write cleaner, more efficient code, especially when dealing with complex data structures or managing asynchronous tasks.

Custom Iterable Objects

An iterable object is any object that implements the Symbol.iterator method. This method returns an iterator, which is an object that provides a next() method to access the next value in the sequence.

Creating a Simple Iterable Object

Let's start by creating a simple iterable object that represents a range of numbers from 1 to a specified limit.

range.js
1class Range {
2constructor(start, end) {
3 this.start = start;
4 this.end = end;
5}
6
7[Symbol.iterator]() {
8 let current = this.start;
9 return {
10 next() {
11 if (current <= this.end) {
12 return { value: current++, done: false };
13 } else {
14 return { value: undefined, done: true };
15 }
16 }
17 };
18}
19}
20
21// Usage
22const range = new Range(1, 5);
23for (let num of range) {
24console.log(num);
25}
Output
1
2
3
4
5

Explanation

  • Range Class: This class represents a range of numbers from start to end.
  • Symbol.iterator Method: This method returns an iterator object. The iterator has a next() method that returns the next value in the sequence.
  • for...of Loop: This loop iterates over each value returned by the iterator.

Common Mistakes

  • Forgetting [Symbol.iterator]: Always ensure your iterable object implements the Symbol.iterator method to make it iterable.
  • Incorrect Return Values: The next() method must return an object with value and done properties. If done is true, iteration stops.

Generator Functions

Generator functions are a special type of function that can be paused and resumed, allowing them to generate a sequence of values over time. They are defined using the function* syntax.

Creating a Simple Generator Function

Let's create a generator function that yields numbers from 1 to a specified limit.

numberGenerator.js
1function* numberGenerator(limit) {
2for (let i = 1; i <= limit; i++) {
3 yield i;
4}
5}
6
7// Usage
8const gen = numberGenerator(5);
9for (let num of gen) {
10console.log(num);
11}
Output
1
2
3
4
5

Explanation

  • function* Syntax: This syntax defines a generator function.
  • yield Keyword: The yield keyword pauses the execution of the function and returns the yielded value. The function can be resumed later from where it left off.

Advantages of Generators

  • Memory Efficiency: Generators generate values on-the-fly, so they don't require storing all values in memory at once.
  • Asynchronous Operations: Generators are often used with async/await to handle asynchronous operations in a more readable and manageable way.

Practical Example: Fibonacci Sequence Generator

Let's create a practical example of a generator function that generates the Fibonacci sequence up to a specified limit.

fibonacciGenerator.js
1function* fibonacci(limit) {
2let [a, b] = [0, 1];
3while (a <= limit) {
4 yield a;
5 [a, b] = [b, a + b];
6}
7}
8
9// Usage
10const fibGen = fibonacci(21);
11for (let num of fibGen) {
12console.log(num);
13}
Output
0
1
1
2
3
5
8
13
21

Explanation

  • Fibonacci Sequence: This generator function generates the Fibonacci sequence by starting with 0 and 1, then yielding each subsequent number.
  • While Loop: The loop continues until the current Fibonacci number exceeds the specified limit.

Summary

ConceptDescription
IteratorsObjects that implement the Symbol.iterator method to provide a sequence of values.
GeneratorsFunctions defined with function* syntax that can be paused and resumed, yielding values over time.
Custom IterableAny object implementing [Symbol.iterator] to make it iterable.
Yield KeywordPauses the generator function and returns a value.

What's Next?

In the next tutorial, we'll explore JavaScript Proxies, which allow you to intercept and redefine fundamental operations for objects. This will give you even more control over how objects behave in your code.

Stay tuned!


PreviousJavaScript Modules (import/export)Next JavaScript Proxies

Recommended Gear

JavaScript Modules (import/export)JavaScript Proxies