Open In App

What is the yield Keyword in JavaScript?

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The yield keyword in JavaScript is used to pause and resume a generator function asynchronously. A generator function works similarly to a normal function, but instead of returning values with return, it uses yield.

This allows for the function's execution to be paused and resumed at specific points. The yield expression returns an object containing two properties: value, which holds the yielded value, and done, a boolean that indicates whether the generator function has been completed (true) or is still in progress (false).

Pausing a yield pauses the generator, and it resumes when the next() method is called. The function continues executing until it encounters another yield or return statement.

Example 1: This example shows the usage of yield keyword in JavaScript.

javascript
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
0
1
2

Example 2: This example shows the usage of yield keyword in JavaScript.

javascript
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)
}

let generator = geeksforGeeks();

//return undefined
console.log(generator.next()); 

//return Welcome to GFG 
console.log(generator.next()); 

Output
{ value: 'Welcome to GFG', done: false }
Hello World  undefined
{ value: undefined, done: true }

Next Article
Article Tags :

Similar Reads