What is the difference between `var functionName = function() {}` vs `function functionName() {}`?

· · 2786 views

What are the purposes behind utilizing these two different methods and what are the upsides and downsides of each? Is there anything that can be done with one method that isn't possible with the other?

var functionOne = function() {
    // Some code
};

vs

function functionTwo() {
    // Some code
}
0
1 Answer

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

// TypeError: functionOne is not a function
functionOne();

var functionOne = function() {
  console.log("Hello!");
};

And, a function declaration:

// Outputs: "Hello!"
functionTwo();

function functionTwo() {
  console.log("Hello!");
}

function declarations defined inside blocks were taken care of conflictingly between browsers. Strict mode (introduced in ES5) settled this by scoping function declarations to their enclosing block.

0

Please login or create new account to participate in this conversation.