xRobot xRobot - 1 year ago 80
Javascript Question

Is there a difference from these 2 functions?

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;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download