Daniel Weibel
Sep 5, 2018 · 2 min read

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.

    Written by

    Systems Programming | Software Development | Cloud Engineering | UNIX/Linux | Java | Go| Kubernetes | AWS

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade