There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.
A function declaration, that is:
function doSomething () {}
Is hoisted entirely to the top of the scope (and like let
and const
they are block scoped as well).
This means that the following will work:
doSomething() // works!
function doSomething() {}
A function expression, that is:
[const | let | var] = function () {} (or () =>
Is the creation of an anonymous function (function () {}
) and the creation of a variable, and then the assignment of that anonymous function to that variable.
So the usual rules around variable hoisting within a scope -- block-scoped variables (let
and const
) do not hoist as undefined
to the top of their block scope.
This means:
if (true) {
doSomething() // will fail
const doSomething = function () {}
}
Will fail since doSomething
is not defined. (It will throw a ReferenceError
)
If you switch to using var
you get your hoisting of the variable, but it will be initialized to undefined
so that block of code above will still not work. (This will throw a TypeError
since doSomething
is not a function at the time you call it)
As far as standard practices go, you should always use the proper tool for the job.
Axel Rauschmayer has a great post on scope and hoisting including es6 semantics: Variables and Scoping in ES6
var doSomething = <function def>;
. 4) "Should all functions be defined this way in ES6?" Seems to cumbersome to me. I like function declarations. Everyone their own.const
. Do you want to prevent yourself from overriding the function? I'd assume you know your code to not do this anyway. Do you want to express the intent ofdoSomething
, i.e. that it holds a function and does not change its value? I think function declarations communicate this intent clearly as well. So, if you need "runtime protection" from overriding, go for it. Otherwise I don't see much benefit. Of course if you primarily used to usevar foo = function() {};
, I would useconst
instead ofvar
.const
at all.const
instead offunction
to define a "function" is a regression in readability. I just started JS again after a 4-5 year hiatus and came across a bunch ofconst
to declarefunction
code and it is wrecking my brain.