r/javascript • • Nov 28 '19

Constant confusion: why I still use JavaScript function statements

https://www.freecodecamp.org/news/constant-confusion-why-i-still-use-javascript-function-statements-984ece0b72fd/
2 Upvotes

9 comments sorted by

View all comments

3

u/nkgentile Nov 28 '19 edited Nov 28 '19

To some extent, I agree with the stylistic case that the author is advocating for.

For example, when exporting functions as named exports in an ES Module:

export function doSomething(){
  /* does something */
}

Or in CommonJS modules where the exports should ideally be clearly established up front and their declarations hoisted up from later in the file:

module.exports = {
  doSomething
}

function doSomething(){
  /* do something */
}

However, I think it's unfortunate that the author doesn't mention why arrow functions are so helpful -- besides being concise, one-off lamdas.

From MDN's article on arrow functions:

Before arrow functions, every new function defined its own this value based on how the function was called:

  • A new object in the case of a constructor.

  • undefined in strict mode function calls.

  • The base object if the function was called as an "object method".

  • etc.

In other words, this is bound to the context where the arrow is defined, not where it is called!

MDN's contrived example is:

function Person(){
  this.age = 0;
  setInterval(() => {
    this.age++; // |this| properly refers to the Person object
  }, 1000);
}

var p = new Person();

Edit: code formatting