Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the key differences between ES6 arrow function and the CoffeeScript fat arrow function?

I am looking to rewrite some CoffeScript code to ECMAScript 2015 (ES6).

Some syntax is very similar such as fat arrow functions:

(param1, param2, paramN) => expression

What are the key differences between ES6 => and CoffeeScript =>?

It would be good to get a heads up from people who already have been in the same situation (converting arrow functions back and forth) and could point out the pitfalls and mistakes to avoid.

like image 735
lazlojuly Avatar asked Jun 09 '26 23:06

lazlojuly


1 Answers

Fat-arrow functions in CoffeeScript translate to your usual JavaScript functions, and bind this to its value in the lexical scope (the scope of definition). Like so:

CoffeeScript

sum = (a, b) =>
  return a + b

JavaScript transpilation

var sum;
sum = (function(_this) {
  return function(a, b) {
    return a + b;
  };
})(this);

Arrow functions in ES2015 always do this this binding.

let arrowFunction = () => this.property

translates to this in ES5

let arrowFunction = (function () { return this.property }).bind(this)

Since this can't be bound to anything else in arrow functions, they can't be used with the new keyword, since that needs to bind this to a new object.

In a "normal" JavaScript function (non-arrow) scope, there's access to a special arguments variable that is "array like" and is useful to access all the arguments that were passed to the function, regardless of the parameter signature. Of course, this is also true in CoffeeScript fat-arrow functions. In my sum example, if someone calls it as sum(1, 2, 3), one can access the third argument by doing argument[2]. Arrow functions don't provide arguments, but have "rest parameters". The latter exists in CoffeeScript too, they call it "splats".

Both CS fat-arrow functions and JS arrow functions support default parameter values. That's not a difference, I know, but worth mentioning IMO.

like image 69
Esteban Avatar answered Jun 13 '26 19:06

Esteban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!