Explore how a basic JavaScript generator pauses and resumes with yield. Starting at 10, it yields 10, then on resume yields 20. This example clarifies the flow of next() calls, how i stays in scope, and why the outputs are 10 and 20—useful for Salesforce JS development and beyond.

Multiple Choice

What is the output of the generator function below after two calls? function* generator(i) { yield i; yield i * 2; } const gen = generator(10); console.log(gen.next().value); console.log(gen.next().value);

The output of the generator function can be explained by looking closely at how generator functions work in JavaScript. The generator function defined here takes an initial value `i`. The `yield` keyword is used to pause the function and return a value, allowing the execution to be resumed later. When the generator function `generator(10)` is called, it initializes a generator object `gen` that starts with `i` set to 10. The first call to `gen.next()` executes the generator up to the first `yield` statement, which yields the value of `i`, so the first call outputs `10`. In the second call to `gen.next()`, the execution resumes right after the first `yield` statement and continues to the next `yield`, which is `i * 2`. Since `i` is still 10, this second `yield` evaluates to `20`, so the second call outputs `20`. Therefore, after two calls to the generator, the output is indeed `10` after the first call and `20` after the second call, leading to the conclusion that the correct answer is that the output is `10` and `20`.

Generators in JavaScript: a small, mighty tool for lazy iteration

If you’ve poked around modern front-end stuff—especially with Salesforce’s Lightning Web Components—you’ve probably bumped into the idea of iterables and asynchronous flows. Generators are a crisp, elegant way to pause a function, hand back a value, and pick up right where you left off. They feel a bit magical at first, but once you get the hang of them, they become a handy companion for handling sequences, streams, or any process you’d like to step through piece by piece.

What a generator actually does

Think of a generator as a function that can suspend its execution at certain points and then resume later. Inside the function, you mark those suspension points with the yield keyword. Each time you call next() on the generator object, the function runs until it hits yield again (or finishes). The value you see is what yield produced at that moment.

This is different from a plain function that runs from start to finish in one go. A generator is lazy; it only produces a value when you ask for it, and it keeps its internal state between asks. That state includes local variables, the current position in the function, and even the value of i or other inputs you used when starting the generator.

A concrete example we can relate to

Here’s a compact example that mirrors the structure you might see in a JavaScript-driven UI flow:

function* generator(i) {

yield i;

yield i * 2;

}

const gen = generator(10);

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

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

Let’s walk through what happens, step by step.

  • The generator is defined to take an initial value i.

  • When you call generator(10), you get back a generator object that “remembers” i = 10.

  • The first gen.next() runs the function until it hits the first yield. It yields i, which is 10.

  • The second gen.next() resumes after that first yield and continues to the next yield, which yields i * 2. With i still equal to 10, that expression yields 20.

So the two console.log calls print 10 and then 20. No mystery there—just the function pausing, resuming, and yielding values one at a time.

Why this matters in a Salesforce JavaScript context

Lightning Web Components lean on modern JavaScript. You’ll often juggle data that arrives over time or in chunks—think streaming data, incremental updates, or orchestrating a sequence of UI steps without blocking the main thread. Generators give you a readable, linear style for these patterns, without resorting to heavy callback spaghetti or more verbose async/await wiring when the scenario fits a stepwise approach.

  • Managing sequences: If you need to walk through a sequence of operations where each step depends on the previous one, a generator keeps your logic tidy. You can yield intermediate results and decide on the next action based on what you already produced.

  • Lightweight stateful logic: Generators preserve their own local state without creating extra objects just to hold intermediate values. That can be handy when wiring up a small state machine for a component’s behavior.

  • Controlled iteration: Because you control when the next piece runs, you can pace data processing, throttle UI updates, or interleave heavy work with UI rendering in a cooperative way.

A closer look at the mechanics

The yield keyword isn’t just a fancy print. It serves two main roles:

  • Returning a value to the caller: The value after yield is what you see when you call next(). In our example, the first yield returns i, so the first next() call reveals 10.

  • Pausing the function: After yielding, the function’s execution stops. The local variables stay as they were, the call stack is unwound to the generator’s paused state, and the next call to next() picks up right where it left off.

When the generator finishes all its yields (or hits a return), subsequent next() calls return an object with done: true, signaling that there’s no more to run. If you’re curious about the exact shape, it’s { value: theYieldedValue, done: false } for ongoing steps, and { value: undefined, done: true } when finished.

A few practical tips to keep in mind

  • The value you get from next() is the yield target. If your generator yields inside a loop or conditional, the values may reflect that path’s behavior.

  • You’re not re-running the function from the very top on every next(). The function resumes exactly where it left off, with all local state intact.

  • You can pass a value into next() as well. The argument to next() becomes the result of the last yield expression inside the generator. That’s a powerful twist you’ll likely see in more advanced patterns.

  • Generators aren’t just for one-shot sequences. They pair nicely with iterable protocols and can be composed with other iterator tools to build flexible data pipelines.

A few caveats and common patterns

  • Don’t overuse them for everything. If your task is straightforward data fetching or simple asynchronous work, async/await often feels more natural. Generators shine when you want explicit, step-by-step control over a sequence.

  • Be mindful of memory if your generator expands into many steps and holds onto large objects. The lazy nature helps, but it’s still good practice to avoid keeping unnecessary references alive.

  • In the browser world, generators map cleanly to modern UI patterns. In the Salesforce ecosystem, you’ll mostly encounter them in client-side code inside LWCs or in tooling that compiles to JavaScript for the browser.

A practical, slightly more involved example

Suppose you’re creating a small UI feature that processes a list of records in chunks, pausing between chunks to keep the interface responsive. A generator can orchestrate that flow:

function* processInChunks(records, chunkSize) {

for (let i = 0; i < records.length; i += chunkSize) {

const chunk = records.slice(i, i + chunkSize);

// Yield the current chunk to the caller (e.g., to render or process)

yield chunk;

// The caller can decide when to resume, maybe after a UI update

}

}

// Example usage

const items = [/* a bunch of records */];

const chunker = processInChunks(items, 5);

let result = chunker.next();

while (!result.done) {

const chunkToProcess = result.value;

console.log('Processing chunk:', chunkToProcess);

// Imagine updating the UI here, then we resume

result = chunker.next();

}

console.log('All chunks processed.');

Here, each yield hands off a slice of the workload, then the caller resumes when ready. It’s a neat pattern for keeping apps responsive, especially when dealing with larger datasets or complex UI interactions.

A quick note on the original example’s takeaway

Returning to the core idea you started with: with a generator created as generator(10), the first next() yields 10, the second next() yields 20. That straightforward sequence is a perfect illustration of the generator’s “pause and resume” rhythm. It’s also a tiny reminder that understanding the flow of i through the function matters. The value you see is not a random hit—it's the result of the current yield expression and the preserved state that sits between each next() call.

Bringing it back to real-world vibes

In real Lightning Web Components development, you’ll often blend declarative templates with some JavaScript logic that runs in response to user actions or data changes. Generators give you a controlled, readable way to model steps that shouldn’t all run at once. It’s a little like choreographing a dance: you cue the next move, you pause to let a visual update land, and you move on when you’re ready. The result is code that’s easier to reason about and maintain—the kind of clarity that helps when you’re debugging a tricky interaction or extending a component later on.

A few final reflections

  • Generators aren’t magic; they’re a language feature that, when used thoughtfully, can simplify complex sequences.

  • They pair well with other modern JS concepts, like iterables, spread syntax, and async constructs, letting you craft elegant flows without drowning in callbacks.

  • For teams building with Salesforce front-end tech, a savvy grasp of generators can speed up how you model progressive enhancements—especially when you need to pace work or reveal data piece by piece.

If you’re curious to experiment, try tweaking the initial value or inserting extra yields in your own version. Notice how the outputs shift, how the flow changes, and how the rest of your code responds to each pause. The more you play with it, the more you’ll spot the places where this lightweight tool can save you from more verbose patterns.

Bottom line: this little generator demonstrates a clean, predictable pattern—one value, then its double, on successive calls. It’s a small window into how JavaScript can model time, state, and sequence in a way that’s both practical and pleasantly intuitive. And in the fast-moving world of front-end development, that clarity is gold.