DEV Community

Evelyn Stender
Evelyn Stender

Posted on • Edited on

4

JavaScript: what are generators (yield)

First of all, what the heck does yield mean? As a non-native English speaker, I found it very confusing. So based on Cambridge Dictionary and Macmillan dictionary, yield is:

To produce something useful such as information or evidence

"Knowing about our past does not automatically yield solutions to our current problems.
yield results/benefits: The search for truth is beginning to yield fruitful results.
"

"A letter found by the FBI last week may yield new clues."

So, now that we know what the word means, let's talk JavaScript.

Generators are a kind of special function that can stop its execution midway and start again from the same point where it stopped after some time. They are basically a combination of functions and iterators.

When you call a generator, it returns an object {value: value, done: true|false}, where value is the value to be yielded and done is a Boolean that tells the generator if .next() function will yield a value or undefined.

To create a generator function we need to use the *:

function* generator(i){ ... }
Enter fullscreen mode Exit fullscreen mode

This is because * tells JavaScript that an iterator object is going to be returned and unlike regular functions, it doesn't start its execution straight away.

Let's have a look at how to use generator functions:

function* generator(i) {  
    yield i + 10;
    yield i + 20;
    yield i + 50;
}

const generate = generator(15);

console.log(generate.next()); // {value: 25, done: false}
console.log(generate.next()); // {value: 35, done: false}
console.log(generate.next()); // {value: 65, done: false}
console.log(generate.next()); // {value: undefined, done: true}
Enter fullscreen mode Exit fullscreen mode

When we call the next() function the execution starts. It executes until it finds the first yield statement and yields the value. When called again, next() will resume the generator function until it finds the next yield statement and this cycle ends when there are no more yields, finishing with {value: undefined, done: true}.

A return statement in a generator will make the generator finish its execution (like any other function), setting the done property true and all other yields after the return will be undefined:

function* generator(i) {  
    yield i + 10;
    yield i + 20;
    return;
    yield i + 50;
}

const generate = generator(15);

console.log(generate.next()); // {value: 25, done: false}
console.log(generate.next()); // {value: 35, done: false}
console.log(generate.next()); // {value: undefined, done: true}
Enter fullscreen mode Exit fullscreen mode

The same applies if an error is thrown: the following yields will all be undefined.

You can also yield another generator function by using yield*:

function* func1() {
  yield 73;
}

function* func2() {
  yield* func1();
}

const iterator = func2();

console.log(iterator.next()) // {value: 73, done: false}
console.log(iterator.next()) // {value: undefined, done: true}
Enter fullscreen mode Exit fullscreen mode

Advantages

  • Lazy loading: it evaluates the value only when there's need for it.
  • Memory efficient: as we only evaluate values when needed, less memory for storing those values is needed.

Risks

  • Generators don’t provide random access like arrays and other data structures.
  • Generators provide one-time access. So you can't iterate through the values again.

Why use generators

I honestly didn't find any use cases for my own code. Researching the internet, I found an interesting article on dev: Use-Cases For JavaScript Generators.

Using JavaScript generators to optimize APIs

IROEGBU! wrote an amazing post about using generators to optimize APIs, you can check it here.

Sources

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

Top comments (2)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

You quote one possible meaning of yield, but it is actually the wrong one. A second meaning of this word:

to relinquish one's possession of (something, such as a position of advantage or point of superiority)

This is what it's actually about. When you yield, you give up the CPU so another thread of execution can run instead. It's the one and only mechanism for cooperative multithreading: a thread runs until it decides to let another one run for a while.

Also, at the end, instead of "fonts" it should be "sources" :D

Collapse
 
evelynstender profile image
Evelyn Stender

Thank you so much! I'll update!!

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay