Skip to content

Comment on ES6 generators in depthparent

Comments

JavaScript is constrained by backwards compatibility. That’s why the ideal solution, the keyword `generator`, wasn’t possible.

This can't be about backwards compatibility. If it was, they wouldn't have been able to add 'yield, 'await' etc.

I don't agree the keyword "generator" would have been ideal. It wouldn't work when using 'enhanced object literals' [1], where you can declare a method without even using the keyword "function". In this case, if you want the method to be a generator, you can just put an asterisk in front of its name, so it's consistent with the "function*" syntax.

[1] https://babeljs.io/docs/learn-es6/#enhanced-object-literals

FYI, "yield" has been a reserved word since ES5 and "await" is becoming reserved in ES6 (for eventual use in ES7): https://mathiasbynens.be/notes/reserved-keywords

It seems like a word must be reserved for at least one ES version prior to it being used.

What about the "yield" keyword?

It's only valid as a keyword within the `function*` block, so the parser can treat it as an identifier elsewhere. I haven't read the detailed spec, so I'm not sure that this is the standard behavior, but this would be a way to preserve complete backward compatability.

Yes, that’s how it works. `yield` is only reserved in ES5 strict mode. But due to it only being a keyword inside generators, there are no problems in non-strict mode.

Why do you think the current syntax is more backwards-compatible? Vanilla ES5 parsers complain loudly when seeing "function *".

It's the other way around. ES6 needs to support loading ES5 content. They can't make 'generator' a keyword because it was a perfectly fine variable name in ES5.

You are right. My bad.

That would be considered "forward-compatible".

which is strange, considering the `async` keyword in upcoming versions.

AFAICT, `async function` is OK, because you combine a keyword with something that is contextually turned into a keyword. With a single non-keyword that isn’t possble. For example, the following code (a hypothetical ES6 anonymous generator expression) could be an ES5 function call followed by a code block.

    generator (a, b, c) {
        ···
    }

That's why it wasn't included in the ecmascript 6 draft. In es6, "async" and "await" are future-reserved keywords. It's kind of a process of marking variables named "async" as deprecated. The spec authors have to balance compatibility with making the language pleasant to use.

Is there even any situation where "async function(..." or "generator function(..." is currently valid syntax?

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.