Monday, May 20, 2024
34
rated 0 times [  37] [ 3]  / answers: 1 / hits: 16653  / 10 Years ago, mon, january 5, 2015, 12:00:00

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?


More From » ecmascript-6

 Answers
8

The three reasons were:




  1. 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).


  2. 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.


  3. 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.)


[#68310] Thursday, January 1, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;