What is the usage of yield keyword in JavaScript?

JavascriptWeb DevelopmentFront End Technology

The yield keyword is used in JavaScript to pause and resume a generator function. The value of the expression is returned to the generator's caller.

Here’s the syntax, where “exp” is the expression and the optional value is returned by “val”, which is passed to the generator's next() method.

[val] = yield [exp];

Here are the examples:

function* displayRank () {
   var selPlayers= [1, 2, 3, 4];
   for (var a = 0; a < selPlayers.length; a++) {
      yield selPlayers[i];
   }
}

After defining a generator function, use it like the following.

Here displayRank() is the generator function:

var rank = displayRank(); //
// value: 1
alert(rank.next());

// value: 2
alert(rank.next());

// value: 3
alert(rank.next());

// value: 4
alert(rank.next());
// value: undefined

alert(rank.next());
raja
Published on 24-Jan-2018 11:32:51
Advertisements