As seen here, there are some differences between function declaration and function expression.
A function expression has one disadvantage vs a function declaration, if called before its been declared it will give an error.
I would like to know only the advantages to use a function expression as I only seem to see the disadvantage I just named above. I possible with an example...
function expression:
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
function declaration:
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
Summary. In short, use function declarations when you want to create a function on the global scope and make it available throughout your code. Use function expressions to limit where the function is available, keep your global scope light, and maintain clean syntax.
There are some benefits of function expressions over statements, for example they are anonymous functions, they can be used as closures, as arguments to other functions and as IIFEs. Put simply a statement in the execution phase it does not return anything, an expression results to a value, an object is created.
The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.
Function Expression allows us to create an anonymous function which doesn't have any function name which is the main difference between Function Expression and Function Declaration. A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon as it is defined.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With