2

i was wondering what is the differences between this:

Option A:

var elements = ['a', 'b', 'c', 'd'];
elements.forEach(function(e){
    console.log('element is: ' + JSON.stringify(e, null, 2));
});

Option B:

var elements = ['a', 'b', 'c', 'd'];
elements.forEach((e) => {
    console.log('element is: ' + JSON.stringify(e, null, 2));
});

Option B would be better/faster than A? Or is the same?

Thanks

Vladimir Venegas
  • 3,894
  • 5
  • 25
  • 45

1 Answers1

1

Option B uses later syntax for javascript ES6 (also known as ES2015). It is only gradually being supported in browsers and node; usually if you want to use it currently you'll transpile it using something like Babel (this will effectively turn option B's code into option A's).

https://babeljs.io/docs/learn-es2015/

https://strongloop.com/strongblog/an-introduction-to-javascript-es6-arrow-functions/

Mark Williams
  • 2,268
  • 1
  • 11
  • 14
  • Sorry, typing!! – Mark Williams Nov 18 '16 at 18:14
  • 11
    This is misleading. The behavior of `this` in the two cases has important differences. – JohnnyHK Nov 18 '16 at 18:18
  • 2
    Sorry, I realise arrow functions treat 'this' differently, but the original poster was just asking about the syntax generally and the functions quoted don't use 'this'. – Mark Williams Nov 18 '16 at 18:21
  • @JohnnyHK , i don't understand the 'misleading'. What is the difference? – Vladimir Venegas Nov 18 '16 at 18:31
  • 1
    @VladimirVenegas See the note about "how `this` works" in the linked duplicate. @Mark, I understand about the limited scope of the OP's example, but the question is specifically asking about the differences and this answer doesn't mention the biggest one (IMHO). – JohnnyHK Nov 18 '16 at 18:37
  • Fair enough; hopefullythe linked question and the links I added will give a good description of arrow functions and 'lexical this'. – Mark Williams Nov 18 '16 at 18:39