ES6 Arrow Functions
Just noticed earlier today that in Firefox version 22 and above ECMASCript 6’s CoffeeScript-style arrow functions are available:
But this current compromise is enough to not fight too much over:
They are only taking the fat-arrow functionality from Coffee, however, so these arrow functions are always using lexical
this which is nice in cases where you need
this in your function to refer to the
this in scope when the function was defined—not where it was called.
CoffeeScript has two different arrow operators for this purpose:
-> which is the standard way where
this is dependent on calling context, and the “fat arrow”
=> version which provides lexical
In Coffee, the parenthesis are optional if-and-only-if the function requires no arguments. This style is convenient because combined with Coffee’s optional parenthesis on function invocation you can very lightweight syntax for common things like:
If the function you’re defining accepts named arguments at all, you must provide the parens:
In ECMAScript 6 arrow functions, for some reason, the parens are optional when the function accepts only one named argument, and are required for all other cases—including when no arguments are declared.
This seems odd and error-prone. By making the parens optional only on the case of one named argument, you really aren’t saving me much at all. In fact, I think without them there makes it even more confusing looking: why is this identifier here? Where did I declare this? Oh, I’m declaring it right now. On the other side, having a pair of empty parens makes me feel like I have leftover cruft from a refactor until I look after it and see the
=> and think Ah, this is a function.
Another slight quirk: you may have noticed the case where my ES6 arrow-function didn’t have a return statement. If you’re familiar with Ruby, Coffee, or other such languages, you may be familiar with this implicit return of the last expression evaluated. Don’t be fooled however, this rule only applies to arrow functions that are only one expression.
We So Excited
Update: If you’d like to use ES6 arrow functions now you can play around with Square’s
es6-arrow-function project from Github. Seems like you could include it in your Grunt build process to extrapolate arrow functions you write in your code into their ES5 equivalents.