How to Yield an Object in JavaScript?

Estimated read time 1 min read

In JavaScript, the yield keyword is used in generator functions to return a value and pause execution, allowing the caller to resume the generator function later. Here’s an example of a generator function that yields an object:

function* generateData() {
  yield { name: "John", age: 30 };
  yield { name: "Jane", age: 35 };
  yield { name: "Jim", age: 40 };
}

let generator = generateData();
console.log(generator.next().value); // Output: { name: "John", age: 30 }
console.log(generator.next().value); // Output: { name: "Jane", age: 35 }
console.log(generator.next().value); // Output: { name: "Jim", age: 40 }

In this example, the generator function generateData yields an object on each iteration. When the next method is called on the generator, the generator function resumes execution and returns the next value. When there are no more values to return, the generator function automatically returns an object with the done property set to true.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply