r/javascript • u/pmz • 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/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
0
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:
Or in CommonJS modules where the exports should ideally be clearly established up front and their declarations hoisted up from later in the file:
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:
A new object in the case of a constructor.
undefinedin strict mode function calls.The base object if the function was called as an "object method".
etc.
In other words,
thisis bound to the context where the arrow is defined, not where it is called!MDN's contrived example is:
Edit: code formatting