Hello, my name is: Amy

Explain the differences on the usage of foo between `function foo() {}` and `var foo = function() {}`

function foo() {} has the name foo directly after the word function and is what is called a function declaration.

var foo = function() {}; is called a function expression and doesn't require a name after the word function. Because of this, these functions are considered anonymous.

Outside of the physical structure of the code, the important difference between these two can be seen when the code is executed:

Function Declarations

Function declarations are actually hoisted up to the top of their scope, so you can define a function declaration after it is used in code without getting an error:

var result = foo();

function foo() {}

JavaScript engine interprets code as:

//compilation
var result;
function foo() {}

//execution
result = foo();

Function declarations get hoisted to the top before executing, and the declaration actually includes the function.

Function Expressions

Because function expressions are only referenced through a variable, only the variable declaration (var foo) is hoisted at runtime , and not the assignment (= function() {}).

The function expression executes as follows:

var result = foo();
var foo = function() {};

JavaScript engine interprets code as:

//compilation
var result;
var foo;

//execution
result = foo(); // --> Error: foo is not a function
foo = function() {};

Comments