How to Use the Yield Keyword in JavaScript?

Estimated read time 1 min read

The yield keyword is used in JavaScript to implement generator functions. A generator function is a special type of function that can be paused and resumed, allowing for the creation of iterators.

Here is an example to demonstrate how to use the yield keyword in JavaScript:

function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

var iterator = generator();
console.log(iterator.next().value); // Output: 1
console.log(iterator.next().value); // Output: 2
console.log(iterator.next().value); // Output: 3

In this example, the generator function generator uses the yield keyword to return a sequence of values. The function is called using the generator function, which returns an iterator. The iterator.next method is used to get the next value in the sequence, and the value property is used to access the actual value.

Note that generator functions are only supported in modern browsers and Node.js, and may not be available in older browsers. To use generator functions in older browsers, you may need to use a transpiler such as Babel.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply