Summary
The yield
keyword is used to pause and resume a generator function.
Syntax
yield [[expression]];
-
expression
-
The expression to return. If omitted,
undefined
is returned instead.
Description
The yield
keyword causes generator function execution to pause and return the current value of the expression following the yield
keyword. It can be thought of as a generator-based version of the return
keyword.
The yield
keyword actually returns an object with two paramters, value
and done.
value
is the result of evaluating the yield
expression, and done
is a bool indicating whether or not the generator function has fully completed.
Once paused on a yield
statement, code execution for the generator cannot resume unless invoked externally by calling the generator's next() method. This allows for direct control of the generator's execution and incremental return values.
Examples
The following code is the declaration of an example generator function, along with a helper function.
function *foo(){ yield; yield "foo"; yield "bar"; yield "hello world"; };
Once a generator function is defined, it can be used by contructing an iterator as shown.
var iterator = foo();
Examples needed here.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 6 (ECMA-262) | Draft |
Browser compatibility