0

So, if we take this function for example:

function executeCallback (callback) {
  callback();
}

Now, it doesn't matter if I place a fat arrow or a normal function, both will work, like these:

executeCallback(function () {
  alert('This is a function');
})

executeCallback(() => {
  alert('This is a fat arrow function');
})

So, except for shorter syntax. What exactly is the difference between both and how does it effect object oriented programming?

FlorisdG
  • 754
  • 5
  • 11
  • 31
  • 7
    The way `this` is bound differs fundamentally. [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) - oh also there can be an implicit `return` – Pointy Mar 10 '17 at 15:18
  • I did notice that indeed. But is that the only difference between both? – FlorisdG Mar 10 '17 at 15:20

2 Answers2

2

For more in depth info, see this answer on SO. Also, See this here.

A Few Reasons


More intuitive handling of current object context.

ES6 Arrow

this.nums.forEach((v) => {
    if (v % 5 === 0)
        this.fives.push(v) //this actually points to the context of the callback
});

Ecmascript 5

//  variant 1
var self = this;
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        self.fives.push(v);
});

//  variant 2
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}, this);

//  variant 3 (since ECMAScript 5.1 only)
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}.bind(this));

More expressive closure syntax.

ES6 Arrow

odds  = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums  = evens.map((v, i) => v + i)

Ecmascript 5

odds  = evens.map(function (v) { return v + 1; });
pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
nums  = evens.map(function (v, i) { return v + i; });
Community
  • 1
  • 1
Abdullah Rasheed
  • 3,562
  • 4
  • 33
  • 51
0
  • the arrow function automatically bind the current context to the this so you won't need to do myfunction.bind(this, args)
Fanyo SILIADIN
  • 802
  • 5
  • 11