Can someone explain to me: why are generator functions in ES6 marked by asterisk symbol?
For example, instead of:
function *someGenerator() {
yield 1;
yield 2;
yield 3;
}
we could write:
function someGenerator() {
yield 1;
yield 2;
yield 3;
}
or even:
var someGenerator = () => {
yield 1;
yield 2;
yield 3;
}
var someObject = {
someGenerator() {
yield 1;
yield 2;
yield 3;
}
}
The JS compiler can detect that someGenerator
contains yield
operator at the parse time and make a generator from this function.
Why is detection of yield
existence not enough?
The three reasons were:
Readability. A generator is quite different from a function, and the difference should be immediately visible (that is, without examining the whole implementation in search for a yield).
Generality. It should be naturally possible to write generators that do not yield, and only return directly. Moreover, commenting out part of the body (e.g. for debugging) should not silently change whether something is a generator.
Compatibility. Only strict mode reserved 'yield' as a keyword, but it was made a goal for ES6 that all new features are also available in sloppy mode (an unfortunate decision IMHO, but nevertheless). Moreover, even in strict mode there are many parsing subtleties around 'yield'; for example, consider default arguments:
function* g(a = yield(2)) { 'use strict' }
Without the *
, the parser could only decide how to parse the yield after it has seen the body of the function. That is, you would need infinite look-ahead, or back-tracking, or other hacky techniques to deal with this.
I should note that (1) and (2) are already reason enough.
(Full disclosure: I am a member of the EcmaScript committee.)