Why doesn't ES6 have thin-arrow functions?
https://softwareengineering.stackexchange.com/questions/306082
-
10-12-2020 - |
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?
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:
- Having two arrow syntaxes with subtly different semantics would increase complication and confusion.
- The dynamic this binding of function() and
->
was deemed rarely useful, and a foot-gun. - If you really need dynamic this binding, you can still use function(), having a shortcut syntax wasn't very helpful.