Can I use ES6's arrow function syntax with generators? (arrow notation)
No, in ES6 you can't use arrow functions (=>
) as generators (function*
). The arrow syntax misses out on the yield
party, and that's where generators shine.
function* myGen() {
yield 'Sorry arrow functions, you are not invited!';
}
Generator functions: A closer view
Generators in JavaScript are special. They've got a unique "pause-play" feature which is a boon for asynchronous programming, controlling functions like a DJ at a disco. Here, the yield
and return
statements are like the DJ's buttons, making functions dance at your command.
Contrarily, arrow functions are anonymous, on a first-name basis with this
within their scope. Their shorter syntax gives them a stylish edge, but unfortunately they lack the guts to yield.
Currently, the TC39 proposal for generator arrow functions is under consideration, marking the future possibility of generators and arrow functions uniting for an even more powerful feature. The async iteration proposal hints at this.
Watch your environment before you play
While playing with generators, make sure your Node.js version (prior v0.11.14) isn't allergic to ES6 features. A programming environment compatibility test is necessary.
While generators are powerful, they are no superheroes. They might not be the best fit for all async operations, and sometimes Promises and async/await patterns beat them to it.
Generators and arrow functions share a common pain point too, they are both forbidden from using the break
and continue
statements with outer non-iterable blocks. A bug bear to be aware of when coding.
When arrow functions fail the constructor test
Arrow functions don't have a prototype
to call their own, making them flunk the generator's constructor function test. This makes them stick out in the roster of generators' prototype functions (next, return, throw) and thus, they don't blend in.
Remember, generators come with a membership card (prototype) that defines their iterator behaviour. The lack of this in arrow functions becomes their major #prototypeFOMO.
The future: Arrow Generators?
Well, ES6 hasn't made peace with the idea of an arrow function turning into a generator yet. But keeps hope alive if the TC39 would weave a magic wave in the upcoming specifications, breathing life into this possibility. The proposal-generator-arrow-functions repository is a living testament to these future hopes, a space to keep an eye on with your fingers crossed.
Was this article helpful?