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

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

5

u/Peribanu Nov 28 '19

The hoisting of function declarations is a really important point. Because most people probably transpile using babel, I wonder how much invalid code is floating around that only runs because it gets turned into old-style function declarations by babel...

4

u/Potato-9 Nov 28 '19

I skimmed this bit I think it misses one,

Const foo = () => throw 'example'

This will be anonymous in a stack trace, where as there named function will show foo was the problem.

Although I feel like JS engines have got better about this now?

3

u/AwesomeInPerson Nov 28 '19

Why? Function expressions get their name from the variable they're assigned to – it's part of the spec. :)

Try it! :)

const iAmNamed = () => { /* */ }
console.log(iAmNamed.name)

1

u/gigastack Nov 28 '19

Agreed on some points, but for callbacks and inline functions like map/forEach, it's arrow functions all the way. Ditto for class methods in a React component. Basically, I mostly use arrow functions but it depends on the type of code you're writing.

2

u/MrDilbert Nov 28 '19

I think it was mentioned at the end of the article that arrow functions are still the better (i.e. more readable/understandable) option for callbacks and array functions.

-5

u/ArmandN Nov 28 '19

Finally, some sanity!

0

u/[deleted] Nov 28 '19

[deleted]

2

u/[deleted] Nov 28 '19

[removed] — view removed comment

3

u/snejk47 Nov 28 '19

The whole article.