JavaScript – Function Declarations vs. Function Expressions

Here’s an example of a function declaration in JavaScript:

    function sayMyName() {

Looks very familiar. And is probably the most obvious way programmers have created functions since the beginning of time JavaScript.

In JavaScript, everything is an object. What happens internally is this declaration gets converted into an expression.

What’s an expression? An expression is any statement that produces a value.

Thus, a function expression becomes:

    var sayMyName = function() {

Function declarations try to hide the fact that the function is indeed an object.

While this may be okay in some cases, it could create confusion when the function is actually being used as a object i.e. being returned, passed around, modified etc.

JavaScript programming (and the programming world in general) is becoming more functional by the day, and it may be a better practice to avoid function declarations altogether in favor of function expressions.

But why? Hoisting.

Function declarations are automatically “hoisted”. The compiler automatically expresses all function declarations at the top of the code regardless of where in the code the function is declared.

This may or may not be a problem depending on the scope-complexity of your code. However it is something that happens automatically, whether you want it or not, and it may be advisable to take such control away from the compiler.

Especially since scoping is very different in JavaScript compared to traditional languages. More on JavaScript scoping in a future blog post.