Function Expression vs Function Statement - jellyfish-tom/TIL GitHub Wiki
[SOURCES]
- https://www.youtube.com/watch?v=MY0UBGX2FtA
- https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
Function Statement / Function Declaration
Just a declaration
function foo() {
}
Function Declarations are officially prohibited within non-function blocks (such as if) . However all browsers allow them and interpret them in different ways.
Function Expression
Any valid unit of code that resolves to a value. So: definition + assignment
let foo = function() { //using anonymous function
}
// it can be named also
let foo = function bar() {
console.log("am confused");
}
Function Declaraiton vs Function Expression
- Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
- Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code.
Similar to the var statement, function declarations are hoisted to the top of other code. Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.
IIFE (Immediately Invoked Function Expression)
Code that is defined and immediately runned in oneliner, without syntactic separation between definition and call.
(function foo(){
console.log("I got runned!");
})();
This on the other hand, will not work.
function foo() {
console.log("Not runned:(");
}();
cause this actually translates to:
function foo() {
console.log("Not runned:(");
}
();
It needs to be wrapped with parentheses. Everything wrapped with parentheses will be interpreted as an expression.
It can be used to narrow scope, often libraries use that to separate their code from the client (program that will use them) code. Everything inside an expression (variable, function, whatever) will not be accessible outside of an expression.