What’s the yield keyword in JavaScript?
Last Updated :
20 Sep, 2019
yield keyword is used to resume or pause a generator function asynchronously. A generator function is just like a normal function but the difference is that whenever the function is returning any value, it does it with the help of ‘yield’ keyword instead of return it. Yield can’t be called from nested functions or from callbacks.
The yield expression returns an object with two properties, “value” which is the actual value and “done” which is a boolean value, it returns true when generator function is full completed else it returns false.
If we pause the yield expression, the generator function will also get paused and resumes only when we call the next() method. When the next() method is encountered the function keeps on working until it faces another yield or returns expression.
Example 1:
function * showPrices(i) {
while (i < 3) {
yield i++;
}
}
const gfg = showPrices(0);
console.log(gfg.next().value);
console.log(gfg.next().value);
console.log(gfg.next().value);
|
Output:
Example 2:
function * geeksforGeeks() {
yield;
gfg(yield "Welcome to GFG" );
}
function gfg(x) {
console.log( "Hello World " , x)
}
var generator = geeksforGeeks();
console.log(generator.next());
console.log(generator.next());
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...