LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Iterators, Generators and Yield in JavaScript

Iterators, Generators and Yield in JavaScript. These concepts help us access data one item at a time instead of processing everything together. We use them when working with arrays, collections, large datasets and custom data sequences. Let's understand how they work and how to write them in JavaScript.

Iterators, Generators and Yield in JavaScript: A Practical Guide

Quick Answer: Iterators let JavaScript read values one at a time. Generators make it easier to create custom iterators using function* and yield. They are useful when we want to process data step by step without creating every result upfront.

An iterator controls how values are read. A generator provides a simple way to build that iterator.

1. Why Do We Need Iterators and Generators?

Imagine a school manages exam results for 10,000 students. The school wants to prepare reports one student at a time.

Should the application create every report before showing the first one? Think about the memory and processing this could need.

The problem without generators

We can create an array containing every report. Then, we can read each report using an index.

Example 1: Creating all student reports upfront

This example creates three reports before processing them.

const students = [
  { name: "Ravi", marks: 82 },
  { name: "Priya", marks: 91 },
  { name: "Arjun", marks: 76 }
];

const reports = students.map((student) => ({
  name: student.name,
  result: student.marks >= 40 ? "Pass" : "Fail"
}));

for (let index = 0; index < reports.length; index++) {
  console.log(reports[index]);
}

Expected output

 { name: 'Ravi', result: 'Pass' }
{ name: 'Priya', result: 'Pass' }
{ name: 'Arjun', result: 'Pass' }

This works, but it gets harder when reports become large.

What goes wrong as data grows?

  1. We create all report objects before reading the first one.
  2. Large result collections can consume more memory.
  3. We may calculate reports that nobody reads.
  4. Custom reading logic can become difficult to reuse.

Now think about 10,000 students. We may only need the first few reports.

The solution: produce each report when requested

A generator can pause after producing one report. It continues when the caller requests another value.

Example 2: Generating student reports on demand

The generator creates one report each time the caller asks for a value.

function* studentReports(students) {
  for (const student of students) {
    yield {
      name: student.name,
      result: student.marks >= 40 ? "Pass" : "Fail"
    };
  }
}

const reports = studentReports(students);

console.log(reports.next().value);
console.log(reports.next().value);
console.log(reports.next().value);

Expected output

{ name: 'Ravi', result: 'Pass' }
{ name: 'Priya', result: 'Pass' }
{ name: 'Arjun', result: 'Pass' }
Creating all reports versus generating reports on demand
Without a generator With a generator
Creates the complete report array. Produces each report when requested.
Stores all generated reports in the array. Does not need to store all generated reports.
Uses array indexes to read values. Uses the iterator's next() method.
May calculate unused reports. Can stop before generating remaining reports.

The idea to remember

  • Iterable = a value that can provide an iterator.
  • Iterator = an object that returns values one at a time.
  • next() = asks the iterator for its next result.
  • Generator = a function that creates an iterator.
  • yield = returns a value and pauses the generator.
  • done = tells us whether the iterator has finished.

2. What Is an Iterable in JavaScript?

An iterable is an object that supports the Symbol.iterator method.

This method returns an iterator. Arrays, strings, maps and sets are common iterables.

For example, an array of students is iterable. We can read it with for...of.

Example 3: Reading an iterable array

const studentNames = ["Ravi", "Priya", "Arjun"];

for (const name of studentNames) {
  console.log(name);
}

Expected output

Ravi
Priya
Arjun

The for...of loop gets an iterator internally. It repeatedly calls next() until iteration finishes.

3. What Is an Iterator?

An iterator is an object with a next() method.

Each call returns an object containing two properties.

  • value contains the current item.
  • done tells us whether iteration has finished.

When done becomes true, there are no more values to read.

Understand the iterator protocol

Protocol = a set of rules that objects follow.

The iterator protocol says that next() must return an iteration result.

Draw.io-style flow: How an iterator works

Student report reading sequence · Automatic workflow animation

Caller Requests next() Iterator Runs next() logic Iteration result value + done Continue or finish request result check done

The animation follows a request through the iterator. The returned result tells the caller whether to continue.

Create an iterator manually

We can build an iterator without using a generator. We must manage its current position ourselves.

Example 4: A custom iterator for student names

const studentNames = ["Ravi", "Priya", "Arjun"];

const studentIterator = {
  index: 0,

  next() {
    if (this.index < studentNames.length) {
      return {
        value: studentNames[this.index++],
        done: false
      };
    }

    return {
      value: undefined,
      done: true
    };
  }
};

console.log(studentIterator.next());
console.log(studentIterator.next());
console.log(studentIterator.next());
console.log(studentIterator.next());

Expected output

{ value: 'Ravi', done: false }
{ value: 'Priya', done: false }
{ value: 'Arjun', done: false }
{ value: undefined, done: true }

Notice how the iterator remembers its current index. Every call moves it forward.

Important: An iterator is usually a one-way reading process. When it finishes, calling next() again normally keeps returning done: true.

4. What Is a Generator Function?

A generator is a special function that can pause and continue later.

We write a generator function using the function* syntax.

Calling it does not immediately run its body. It returns a generator object.

A generator object is also an iterator and an iterable.

That means it supports both next() and Symbol.iterator.

Example 5: A simple student name generator

function* studentNames() {
  yield "Ravi";
  yield "Priya";
  yield "Arjun";
}

const students = studentNames();

console.log(students.next());
console.log(students.next());
console.log(students.next());
console.log(students.next());

Expected output

{ value: 'Ravi', done: false }
{ value: 'Priya', done: false }
{ value: 'Arjun', done: false }
{ value: undefined, done: true }

The generator stops at each yield. It remembers where it stopped.

The next next() call continues from that exact position.

5. How Does the yield Keyword Work?

yield returns a value from a generator. It also pauses execution.

The generator continues when its caller requests another value.

Follow the generator execution

Draw.io-style flow: Generator pause and resume

One student report is produced at each yield point

next() request Start or resume generator yield report for Ravi Returns value and pauses Caller reads the report Generator remains paused Next request resumes Continues after the last yield More values or done: true

Each request resumes the generator from its previous pause. Execution ends when the generator returns.

Use yield with calculations

We can calculate a result before yielding it. The caller receives the calculated value.

Example 6: Yield calculated student results

function* calculateResults(students) {
  for (const student of students) {
    const result = student.marks >= 40 ? "Pass" : "Fail";

    yield {
      name: student.name,
      marks: student.marks,
      result
    };
  }
}

const students = [
  { name: "Ravi", marks: 82 },
  { name: "Priya", marks: 91 },
  { name: "Arjun", marks: 32 }
];

for (const report of calculateResults(students)) {
  console.log(report);
}

Expected output

{ name: 'Ravi', marks: 82, result: 'Pass' }
{ name: 'Priya', marks: 91, result: 'Pass' }
{ name: 'Arjun', marks: 32, result: 'Fail' }

The generator calculates one result before each yield. The loop requests the next result automatically.

6. Understanding the Generator Object

Calling a generator function returns a generator object. This object provides methods for controlling execution.

Important generator object methods
Method Purpose
next(value) Continues execution and returns the next result.
return(value) Ends the generator and returns the supplied value.
throw(error) Throws an error at the generator's suspended position.

Using next() with a value

The value passed to next() becomes the result of the suspended yield expression.

The first next() argument is ignored. The generator has not reached a yield yet.

Example 7: Passing a value into a generator

function* collectFeedback() {
  const firstAnswer = yield "Enter the first feedback";
  console.log("First feedback:", firstAnswer);

  const secondAnswer = yield "Enter the second feedback";
  console.log("Second feedback:", secondAnswer);
}

const feedback = collectFeedback();

console.log(feedback.next());
console.log(feedback.next("Good teaching"));
console.log(feedback.next("Clear examples"));

Expected output

{ value: 'Enter the first feedback', done: false }
First feedback: Good teaching
{ value: 'Enter the second feedback', done: false }
Second feedback: Clear examples
{ value: undefined, done: true }

Remember: A value passed to next() is received by the previous suspended yield. The first next() starts the generator.

Using return() to stop a generator

The return() method ends the generator immediately. It can also provide the final result value.

Example 8: Stopping report generation

function* studentReports() {
  yield "Ravi report";
  yield "Priya report";
  yield "Arjun report";
}

const reports = studentReports();

console.log(reports.next());
console.log(reports.return("Report generation stopped"));
console.log(reports.next());

Expected output

{ value: 'Ravi report', done: false }
{ value: 'Report generation stopped', done: true }
{ value: undefined, done: true }

Using throw() to handle an error

The throw() method throws an error inside the suspended generator. The generator can catch it using try...catch.

Example 9: Handling a report processing error

function* processReports() {
  try {
    yield "Report started";
    yield "Report is ready";
  } catch (error) {
    yield "Report error: " + error.message;
  }
}

const report = processReports();

console.log(report.next());
console.log(report.throw(new Error("Missing marks")));
console.log(report.next());

Expected output

{ value: 'Report started', done: false }
{ value: 'Report error: Missing marks', done: false }
{ value: undefined, done: true }

7. What Is yield* in JavaScript?

yield* delegates generator work to another iterable or generator.

It forwards values from that source to the caller.

For example, a school may prepare separate reports for different classes. One generator can combine the results from smaller generators.

Example 10: Combining reports from two classes

function* classTenReports() {
  yield "Ravi - Class 10";
  yield "Priya - Class 10";
}

function* classTwelveReports() {
  yield "Arjun - Class 12";
  yield "Meera - Class 12";
}

function* allSchoolReports() {
  yield* classTenReports();
  yield* classTwelveReports();
}

for (const report of allSchoolReports()) {
  console.log(report);
}

Expected output

Ravi - Class 10
Priya - Class 10
Arjun - Class 12
Meera - Class 12

Here, yield* forwards values from both generators. The outer generator controls the complete sequence.

8. Lazy Evaluation and Memory Benefits

Lazy evaluation means calculating a value only when it is requested.

Generators support this approach. They do not calculate every future value automatically.

Consider a school that needs only the first two reports. A generator can stop after those reports.

Example 11: Read only the first two reports

function* studentReports(students) {
  for (const student of students) {
    console.log("Preparing:", student.name);

    yield {
      name: student.name,
      marks: student.marks
    };
  }
}

const students = [
  { name: "Ravi", marks: 82 },
  { name: "Priya", marks: 91 },
  { name: "Arjun", marks: 76 }
];

const reports = studentReports(students);

console.log(reports.next().value);
console.log(reports.next().value);

Expected output

Preparing: Ravi
{ name: 'Ravi', marks: 82 }
Preparing: Priya
{ name: 'Priya', marks: 91 }

The third report is never prepared. The caller did not request it.

Performance note: Generators can reduce temporary result storage. They do not automatically make every program faster. The source data may still occupy memory, and each requested value still needs processing.

9. Iterators vs Generators

Both provide values one at a time. Their main difference is how we create and manage them.

Iterator and generator comparison
Area Iterator Generator
Creation Usually created manually or by an iterable. Created by calling a generator function.
Syntax Uses a next() method. Uses function* and yield.
State We manage the current state. JavaScript remembers the suspended state.
Pause and resume We implement the behavior. Built into generator execution.
Complexity Can need more manual code. Usually needs less code for sequences.
Best use Custom iteration protocols. Step-by-step value production.

10. Where Do We Use Iterators and Generators?

1. Processing large data sets

We can read records one at a time. This avoids building another complete result array.

2. Pagination

A generator can produce one page of results at a time. The caller requests the next page when needed.

3. Reading files or streams

We can process chunks instead of loading an entire file into memory. The actual file-reading API must support the required streaming behavior.

4. Custom data structures

We can make a class iterable. This lets users read its values with for...of.

5. Infinite sequences

A generator can produce values without a fixed end. The caller decides when to stop.

Example 12: Generating student report numbers

function* reportNumbers() {
  let number = 1;

  while (true) {
    yield "REPORT-" + number;
    number++;
  }
}

const numbers = reportNumbers();

console.log(numbers.next().value);
console.log(numbers.next().value);
console.log(numbers.next().value);

Expected output

REPORT-1
REPORT-2
REPORT-3

Important: Do not use an infinite generator in an unrestricted loop. It will never finish. Always define a stopping condition or limit the number of values requested.

11. Async Iterators and Async Generators

Some data arrives later. For example, a school may request reports from a remote service.

Async iterators support values that become available asynchronously.

An async generator uses async function*. It can use both yield and await.

We can read an async generator using for await...of.

Example 13: An async generator for report batches

async function* reportBatches() {
  yield ["Ravi", "Priya"];
  yield ["Arjun", "Meera"];
}

async function readReports() {
  for await (const batch of reportBatches()) {
    console.log(batch);
  }
}

readReports();

Expected output

[ 'Ravi', 'Priya' ]
[ 'Arjun', 'Meera' ]

This example shows the syntax. Real network or file operations can use await inside the async generator.

12. Common Mistakes and Best Practices

Mistake 1: Calling a generator like a normal function

A generator call returns an iterator. It does not return the first yielded value directly.

Wrong approach

function* studentName() {
  yield "Ravi";
}

const name = studentName();
console.log(name);

Correct approach

const name = studentName();
console.log(name.next().value);

Expected output

Ravi

Mistake 2: Forgetting that generators pause

Code after yield does not run until the next request.

Do not expect the entire generator body to execute immediately.

Mistake 3: Using next() without checking done

Manual iteration should check the done property. Otherwise, code may process an undefined value after completion.

Correct manual iteration

const iterator = studentNames();

let item = iterator.next();

while (!item.done) {
  console.log(item.value);
  item = iterator.next();
}

Mistake 4: Expecting a generator to restart

A completed generator stays completed. Call the generator function again to create a new generator object.

Mistake 5: Using generators for every array operation

Generators are useful for lazy sequences. Arrays are often simpler for small collections and random access.

Best practices

  • Use generators when values should be produced on demand.
  • Use for...of when you do not need manual control.
  • Use yield* to delegate to another iterable.
  • Use async generators for asynchronous value sequences.
  • Always plan how an infinite generator will stop.
  • Keep generator logic focused on producing values.

13. Interview Questions and Answers

1. What is an iterator in JavaScript?

Strong answer: An iterator is an object with a next() method. Each call returns a value and a completion status. We can use it to read data one item at a time.

2. What is a generator function?

Strong answer: A generator is a special function written with function*. It returns an iterator when called. It can pause with yield and continue with the next request.

3. What is the difference between yield and return?

Strong answer: yield produces a value and pauses the generator. The generator can continue later. return ends the generator and marks it as complete.

4. What is the difference between an iterable and an iterator?

Strong answer: An iterable provides an iterator through Symbol.iterator. An iterator provides values through next(). An array is iterable, while its iterator reads its values.

5. What does yield* do?

Strong answer: yield* delegates iteration to another iterable or generator. It forwards that source's values through the current generator.

6. How do generators help with memory?

Strong answer: Generators can produce values only when requested. This can avoid creating a second large result collection. They are useful for large or streaming sequences.

7. Can a generator receive values?

Strong answer: Yes. We can pass a value to next(). That value becomes the result of the suspended yield expression. The first next argument is ignored.

8. What is an async generator?

Strong answer: An async generator uses async function*. It can wait for asynchronous work and yield values over time. We usually consume it with for await...of.

What interviewers expect at each level

  • Junior: Explain function*, yield and next().
  • Senior: Explain lazy evaluation, delegation and async generators.
  • Architect: Discuss streaming, memory behavior, backpressure and failure handling in the wider system.

14. Hands-On Practice

Beginner: Create a student name generator

Create a generator that yields five student names. Read them using for...of.

Hint: Use one yield statement for each name.

Intermediate: Generate passing student reports

Create a generator that receives an array of students. Yield only students who scored at least 40 marks.

Expected result: Students with marks below 40 should not appear.

Hint: Use a for...of loop and an if condition before yielding.

Advanced: Build a paginated report generator

Create a generator that accepts student records and a page size. Yield one array for each page.

Expected result: A page size of two should produce batches of two students. The final page may contain fewer records.

Hint: Keep a temporary batch. Yield it when it reaches the page size. Yield the remaining batch after the loop.

15. Frequently Asked Questions

Are generators iterators?

Yes. A generator object implements the iterator protocol. It also supports the iterable protocol.

Can we use generators with for...of?

Yes. Generator objects are iterable. A for...of loop requests values until the generator finishes.

Can a generator have multiple yield statements?

Yes. A generator can contain many yield statements. Each one pauses execution and returns a value.

Can we use yield outside a generator?

No. The yield keyword is valid inside generator functions and generator bodies.

Do generators always improve performance?

No. They can reduce unnecessary result creation. They also add iteration overhead. Choose them when their lazy behavior helps your use case.

Can we use await inside a normal generator?

No. Use an async generator when you need both asynchronous waiting and yielded values.

16. Next Steps and Community

You now understand how JavaScript reads and produces values step by step.

Practice the iterator protocol first. Then build generators with yield and yield*.

Explore Further

Share Your Knowledge

Try these examples and build your own generator. Share your implementation and discuss other ways to process large data sets.

Keep practising. Learn Technology. Build Your Future.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.