Last Updated: February 25, 2016
· steveniseki

Arrow Functions - ES6 and CoffeeScript

<b>CoffeeScript fat and thin arrow functions</b>

In CoffeeScript there are two different types of arrows for defining functions: thin arrows -> and fat arrows =>. The JavaScript function keyword was replaced with the thin arrow. The fat arrow serves as the function keyword and also binds the function to the current context.

This example from Stack overflow shows the difference between the two.

class A
  constructor: (@msg) ->
  thin: -> alert @msg
  fat:  => alert @msg

x = new A("yo")
x.thin() #alerts "yo"
x.fat()  #alerts "yo"

fn = (callback) -> callback()

fn(x.thin) #alerts "undefined"
fn(x.fat)  #alerts "yo"

<b>EcmaScript 6 arrow functions</b>

Arrow functions which have been proposed for ES6, provide the same two features of fat arrow functions in CoffeeScript: lexical scoping of <i>this</i> and cleaner syntax when defining an anonymous function. At this stage arrow functions are only implemented in Firefox 22, Check here for browser compatibility

<b>ES5 anonymous function syntax</b>

var x = [0,1,2]; (x) { 
  console.log(x * x);

<b>ES6 arrow function</b>

let x = [0,1,2]; => console.log(x * x));

<b>Function object with anonymous method</b>

function Person() {
  var self = this;
  self.age = 0;

  setInterval(function growUp() {
  }, 1000);

<b>Function object with arrow function method</b>

function Person(){
  this.age = 0;

  setInterval(() => {
    // this is lexically scoped
  }, 1000);

For some more information and examples on arrow functions check out Mozilla