Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Usage of yield Keyword in JavaScript



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());
Updated on: 2019-10-03T07:08:09+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements