All variables declarations are hoisted on the top of the scope and all function definitions are as well hoisted on the top of the scope. Therefore
console(foo()); // prints foo
function foo(){return 'foo'};
but
console(foo()); // complain foo is not function, it is undefined
var foo = function(){return 'foo'};
the second example is identical to this:
var foo;
console.log(foo());
foo = function(){}
The reasons for using the second expression would stem from your programming logic. for example:
var foo = MY_ENV_VAR ? function(){return true} : function(){return false}
or run the following example for better understanding:
var bar;
if (true) {
function foo(){return 'foo'};
bar = function(){return 'hey'};
} else {
function foo(){return 'another'};
bar = function(){return 'bar'};
}
console.log(foo());
console.log(bar());
the first log will be another
because JS compiler puts the function declaration on the top of the scope and the second declaration just overwrites the first one. While the second log outputs the result of the function assigned in the if statement , which will be hey
.