Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Practice this question and more.


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);

  1. [0, 10], [10, 20]

  2. 20, 20

  3. 10, 20

  4. 0, 10 and 10, 20

The correct answer is: 10, 20

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`.