This is called a function expression:
var foo = function() {}
and this is a function declaration:
function foo() {}
A major difference is that function declarations are "hoisted". Behind the scenes, a function declaration is "hoisted" to the top of its scope and assigned to a variable name - effectively the same as a function expression.
Consider this:
foo(); //logs 'abc'
function() {
console.log('abc');
}
That works fine because foo
will be hoisted. With a function expression, this will fail:
foo(); //foo is not defined!
var foo = function() {
console.log('abc');
}
One thing that's awesome about function expressions is that you can assign their value with an IIFE (Immediately Invoked Function Expression) and have private values and functions like this:
var myFunc = (function() {
function thisWillBeMyFunc() {
doOne();
doTwo();
doThree();
}
function doOne() {
console.log('Action 1!');
}
function doTwo() {
console.log('Action 2!');
}
function doThree() {
console.log('Action 3!');
}
return thisWillBeMyFunc;
}());
myFunc(); //logs the actions
doOne(); //error - not defined!
Live demo (click).
Oh, the wonderful power and flexibility of JavaScript!