1

I have downloaded an open source js code where the developer often create new function in this way:

var log = msg => div.innerHTML += "<br>" + msg;

So, is there a difference with this below ?

function log(msg){
   div.innerHTML += "<br>" + msg;
}
xRobot
  • 22,700
  • 56
  • 163
  • 281
  • 1
    There are some differences between arrow functions and `function foo() {}` functions. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Asad Saeeduddin Oct 29 '16 at 05:55
  • 1
    check this post http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 – Iññoceñt Ùšmâñ Oct 29 '16 at 06:00

1 Answers1

0

There are some differences between arrow functions and function foo() {} functions. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions.

A few I can think of off the top of my head:

  • function foo() {} function definitions are hoisted, which means you can invoke such a function anywhere in the scope that contains its definition. This is not the case for variables containing functions, for which only the declarations are hoisted
  • Arrow functions bind this lexically, which in simple words means that they do not introduce their own this variable. Instead, they simply close over the nearest this variable from an enclosing scope
  • Arrow functions do not have the arguments local variable available for use within the body

All that said, the two functions you have shown should behave identically in most cases, given the caveats mentioned above.

Asad Saeeduddin
  • 43,250
  • 5
  • 81
  • 127