0

I'm still not very familiar with all the ES6 syntax, and I'm starting to learn Vue.js, which makes extensive use of it. So, I find something that puzzles me a bit:

What's the difference between these two methods?

const actions = {
  foo1(num) {
    console.log(num);
  },
  foo2: (num) => {
    console.log(num);
  }
}

actions.foo1(2);

actions.foo2(3);

// output: 2

// output: 3

I guess they are not the same, although they both output their passed value.

Luis Martin
  • 899
  • 2
  • 12
  • 28
  • 1
    The first one is the existing function definition while the second one is declaring an arrow function(using ES6 fat arrow syntax). They are different in terms of preserving the value of `this`. – Niladri Sep 23 '20 at 20:46
  • 1
    the arrow function cannot access to object elements – Mister Jojo Sep 23 '20 at 20:50
  • 1
    but in this case you are not referring to `this` that's why the output is identical for you. A good example would be incrementing a global variable inside a `setTimeOut` . If you use Arrow function it does not create it's own scope instead it will refer to `this` from where it is getting called. – Niladri Sep 23 '20 at 20:50
  • @trincot thanks . edited – Niladri Sep 23 '20 at 20:51
  • 1
    The difference most likely to cause you problems: ["this" and Arrow Functions (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#this_and_Arrow_Functions) – zcoop98 Sep 23 '20 at 20:55
  • Thanks all for your help! – Luis Martin Sep 23 '20 at 21:12

0 Answers0