Question

ES6 added fat-arrow functions (=>), which have two major differences from normal functions:

  • shorter syntax (including implicit return if you use a single-expression body)
  • inherit this from surrounding scope

These are both very useful features, but seem to me completely separate in their value and application – sometimes I want one, or the other, or both, or neither. It seems odd that if I want to use a short-syntax function, I have to also use the this-modifying behaviour. And vice versa. I don't see why these two capabilities are implemented as a single addition to the language.

What if I want to use a short syntax function for its implicit return and brevity (in some context where a full function (..) { return ...} would be slightly less readable), but I want to use this in my function to refer to the calling context? There's no way to do this.

CoffeeScript has both -> and => style functions, and apparently ES6 borrowed the => style from there. So my question is, why didn't ES6 also borrow the -> style?

Was it helpful?

Solution

See the proposal to add arrow functions: http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax1

What it says is:

However, we don’t want CoffeeScript’s ->, it’s confusing to have two arrows and dynamic this binding is an oft-fired footgun.

You can also see some discussion of a previous version of the proposal which did have the -> syntax as well: https://esdiscuss.org/topic/arrow-function-syntax-simplified

It appears to come down to the following:

  1. Having two arrow syntaxes with subtly different semantics would increase complication and confusion.
  2. The dynamic this binding of function() and -> was deemed rarely useful, and a foot-gun.
  3. If you really need dynamic this binding, you can still use function(), having a shortcut syntax wasn't very helpful.
Licensed under: CC-BY-SA with attribution
scroll top