Difference between -> and => in CoffeeScript
Thin arrow functions, -> are used to describe functions.
square = (x) -> x*x
cube = (x) -> x*x*x
pow = (num, power) -> num**power
Equivalent JS:
var cube, pow, square;
square = function(x) {
return x * x;
};
cube = function(x) {
return x * x * x;
};
pow = function(num, power) {
return Math.pow(num, power);
};
Fat arrow functions, => are used to describe functions that are immediately invoked with current scope.
run = () ->
this.names = ["sir", "boast", "a", "lot"];
reproduce = () =>
_this.names.forEach((x)->
console.log(x)
)
reproduce
Output of which is:
var run;
run = function() {
var reproduce;
this.names = ["sir", "boast", "a", "lot"];
reproduce = (function(_this) {
return function() {
return _this.names.forEach(function(x) {
return console.log(x);
});
};
})(this);
return reproduce;
};
run()();
Basically, a = () -> 10 is var a = function(){ return 10; } and a = () => 10 is var a = (function(_this){ var a = function(){ return 10; } })(this);