Advantages to use function expression instead of function declaration?
Along with that very good answer, the only advantage I can see is dynamically changing a function call.
For example this code :
function foo(){
console.log('foo');
}
function bar(){
console.log('bar');
}
var myFn = foo;
myFn();
setInterval(function(){
if(myFn === foo) myFn = bar;
else myFn = foo;
}, 5000);
setInterval(function(){
myFn()
}, 6000);
It will never log the same thing since you reassign a global variable, every innerscope function will change while this code :
function foo(){
console.log('foo');
}
setInterval(function(){
function foo(){
console.log('Changed foo');
}
foo()
}, 5000)
setInterval(function(){
foo()
}, 5000)
Will log 2 different things. You can only change the current scope function, not the global.
My Experiment: function expression we need to use when use that function in different scopes. For example.
function outer(){
function inner(){
}
}
outer();
inner();// Error ...calling inner..will not be found..
-this will not work. But
var inner;
function outer(){
inner=function(){
}
}
outer();
inner();// will work
-this will work