Good point.
Function definition expression
var square = function(x) { return x * x; };Function declaration statement
function square(x) { return x * x; }Hoisting with Function Definition Expressions
With var:
With function definition expressions, you can’t use the function before you define it in the script. What’s hoisted to the top of the script with var is only the variable declaration, not the assignment:
console.log(square); // => undefined
var square = function(x) { return x * x; }So, in the console.log() line, the variable square is already declared, but no value has yet been assigned to it. This is the same as this:
var square;
console.log(square); // => undefined
square = function(x) { return x * x; }With const and let:
With const and let the variable declarations are not hoisted to the top of the script, but this doesn’t change much as you anyway can’t use the function before it is defined:
console.log(square); // => ReferenceError: square is not defined
const square = function(x) { return x * x; }and
console.log(square); // => ReferenceError: square is not defined
let square = function(x) { return x * x; }Hoisting with Function Declaration Statements
On the other hand, with function declaration statements, you can use the function before it is defined in the script:
console.log(square); // => [Function: square]
function square(x) { return x * x; }So, for defining global function, there’s usually no reason to use anything else than a function declaration statement, and so you don’t need to choose between var, const, and let.
Sources: JavaScript: The Definitive Guide.
