Reputation: 33994
I am trying to export a function in a .js file using both normal or arrow function. But I don't understand which is recommended.
Export normal function
module.exports = function(id) {
console.log(id);
};
Export an arrow function
const test = id => {
console.log(id);
}
module.exports = test;
Below are few questions I have in my mind.
If normal function is recommended over an arrow function, then why I am not recommended to use arrow function.
If arrow function is recommended over normal function, then why I am not recommended to use normal function.
How can I understand the recommended one, especially in this scenario of exporting a function?
Upvotes: 5
Views: 11747
Reputation: 622
const App = () => console.log("This is an app.");
export default App;
OR
export const App = () => console.log("This is an app.");
Upvotes: 0
Reputation: 222538
These two snippets aren't identical. First snippet results in anonymous function, while second snippet results in named function, require('...').name === 'test'
(this may be useful for debugging).
A more suitable comparison is
module.exports = function test(id) {
console.log(id);
};
vs
const test = id => {
console.log(id);
}
module.exports = test;
There's no difference between these arrow and regular function in such case because they don't use features that are specific to them (e.g. this
context).
Anonymous arrow function takes less characters to type but this benefit disappears when there's a need to give a function a name via temporary test
variable. They also may result in lesser memory footprint, though this concern can be ignored because the difference is negligible.
Also, named arrow functions can result in more verbose output than regular functions definitions if they are transpiled to ES5:
const test = () => {}
is transpiled to
var test = function test() {}
While it could be:
function test() {}
This isn't a concern for Node.js or other ES6 environment.
TL;DR: if a function needs to have a name for debugging or other purposes, it makes sense to use:
module.exports = function test(id) {
console.log(id);
};
If a function doesn't need a name, it's:
module.exports = id => {
console.log(id);
};
This is true for functions that don't use features specific to these function types.
Upvotes: 10