Open In App
Related Articles

What’s the yield keyword in JavaScript?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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++;
    }
}
  
//creating an object for our function showPrices
const gfg = showPrices(0); 
  
//return 0 because 0 value is passed to the showPrices yield expression
console.log(gfg.next().value); 
  
// return 1
console.log(gfg.next().value); 
  
//return 2
console.log(gfg.next().value); 


Output:

Example 2:




function* geeksforGeeks() {
  
  /*expression paused here and return
  value is undefined as nothing is declared*/
    yield; 
    
    //wait for next() to finish
    gfg(yield "Welcome to GFG"); 
}
  
function gfg(x) {
    console.log("Hello World ", x)
}
  
var generator = geeksforGeeks();
  
//return undefined
console.log(generator.next()); 
  
//return Welcome to GFG 
console.log(generator.next()); 
  
/*done remains false as we have not called next 
so that "Hello World" is still left there to process*/


Output:


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 20 Sep, 2019
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials