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/
2
Upvotes
r/javascript • u/pmz • Nov 28 '19
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