Function Expressions vs Function Declarations In JavaScript

Hello everyone! Today I’m going to talk to you about function expressions, function declarations what’s best to use, when to use and more importantly how to avoid unexpected behavior when using them. A lot of newcomers to JavaScript find this confusing but I’m here to convince you that it’s pretty simple:

This is a function declaration:

function foo(){
	console.log("I am foo");
}

This on the other hand is a function expression:

var foo = function(){
	console.log("I am foo");
}

In either case you execute foo in the same way:

foo();

The same thing applies if foo takes one ore more parameters:

function foo(param1, param2){
	….
}

var foo = function(param1, param2){
	….
}

Then you can call it like this:

foo("bar", 3.14);

So I can use whatever I like best and there is no real difference between the two besides the syntax used during the function definition?
The answer is No

Consider the two following examples:

Example 1:

foo();

function foo(){
	console.log("I am foo");
}

Output: “I am foo”

Example 2:

foo();

var foo = function(){
	console.log("I am foo");
}

Output: Uncaught TypeError: foo is not a function

Why is this happening? The reason has to do with hoisting. When you use a function declaration you can imagine that during the first pass of the compiler the function and variable declarations will be moved to the top of the enclosing function (that’s not exactly what really happens but it’s very convenient to imagine it like that). When you use a function expression, only the variable declaration will be “moved” to the top of the enclosing function. You can visualize the result of hoisting in both examples like this:

Example 1 (after hoisting):

function foo(){
	console.log("I am foo");
}

foo();

Example 2 (after hoisting):

var foo;

foo();

foo = function (){
	console.log("I am foo);
}

As you can see in the second example when the engine executes the statement ‘foo();’ it does not possess sufficient knowledge about foo. At that time it only knows that foo is a variable, the actual assignment takes place later in the code.

This is actually the most important thing between function declarations and function expressions