Javascript function declaration or expression?

You may have heard of the different ways of declaring a function in JavaScript. It may seem a bit intimidating to newcomers as they need to learn and consider more, but actually, they aren’t so important except in a few situations.

There are a couple of different examples out there that demonstrate how choosing one can affect your code, but here, we just take a look at an important point to consider which is about placing functions correctly.

Function Declarations

If you come from a PHP background, you knew it already. It has the same syntax. Using function operator at the beginning of your identifier will do the magic, and just like what you normally do for declaring a variable in Javascript with var keyword, this time, via function keyword you tell the JavaScript engine to create a new function for you.

This type of declaring a function is called Function Declaration.

When you use this variant, your function will be moved invisibly to the top of its scope, meaning that it will be processed before running any line-by-line code in the context. Therefore, it will be accessible anywhere in the code.

As our example shows, we’re calling our function a few line before it is declared, but we’re getting the “Hello!” message successfully because we have used Function Declaration.

Function Expressions

Declaring a function as an expression is nothing more than a regular Javascript expression. Using var keyword plus your identifier is the declaration part, and filling it with your function definition is the instantiation.

The above variant is called Anonymous Function Expression and so only defined when that line is reached.

We can call our function after JavaScript interpreter arrives at its expression.

Declaration is hoisted, not instantiation

It’s critical to notice that declaration will hoist to the top of the scope, not the instantiation. Check the examples:




As the examples show, if you access a variable that’s not declared, you will get a reference error. However, if you use a variable before it’s declared, but you have declared it anywhere within the scope at a later time, you will have access to the variable value which is instantiated with undefined.

In one of our examples, we have declared a variable and set it to hold 10; its declaration is detected, but the value isn’t accessible. It means that variable declaration will hoist, not variable assignment.

Bottom line

Using declarative functions, you’re free to call your functions anywhere in the code (in context) because it is hoisted before, so is accessible. But if you’re using the expression way, you will get an error because you’re calling the instantiation of the variable which holds the function definition, while it is only reachable after it’s declared.