I'm trying to decide what style to use for module-level function definitions.
Here are the options I've considered:
// function expression using an arrow
const foo = (arg)=> {
// ...
};
// function expression with the `function` keyword
const bar = function(arg){
// ...
};
// function declaration
function baz(arg){
// ...
}
I prefer the foo
style, but it seems to be non-standard. Are there considerations against it that I haven't considered? For example, are there significant performance penalties to using function expressions, const
, or arrows, either natively or when transpiling?
Here's what I have so far:
Advantages of using const
with a function expression instead of using a function declaration:
- Nothing is ever hoisted if you only use
const
andlet
: it makes the language simpler to work with. - Using
const
makes the interpreter throw an error if you try to define two functions with the same name in the same scope (this has been surprisingly helpful). - Using
const
lets you say what you mean: most of the time, one wants to define a function, not assign to a variable. - Using
const
instead of a function declaration makes it clearer that functions are values in JS.
Disadvantages of function expressions:
- A function declaration causes both the variable declaration and function body to be hoisted to the top of the current function body (I think). This may actually be helpful if you like to lay your JS files out with function-using code on top and function definitions at the bottom.
I couldn't find any cases where function expressions are harder to debug or where it was harder to use recursion with function expressions.
Advantages of using arrows instead of the function
keyword:
- The fat arrow has simpler semantics in this sense. It's probably better to not ask for new values of
this
andarguments
unless they are really needed.