Immediately Invoked Function Expression
Creating functions:
3 Ways to create a function in JS (Not ES6 or Json notation syntax):
Please see ES6 section to learn about other ways.
Function Statements and Function Expressions
Expressions:
- Unit of code that results in a value - Does not have to save to a variable
Example:
var a;
a = 3 , returns 3
1 + 2 , returns 3
Statements:
- if(a === 3){}, we put an Expressions inside
Function Statements:
- Does not return a value
function greet(){
console.log("Hi")
}
Function Expressions:
- var anonymousGreet = function () {
console.log("hi");
}
- It is an anonymous function, we call it by anonymousGreet()
- Results in an new function object, so it is an Expressions
Function declaration
function example() {
console.log("b");
}
Function expression
var example = function() {
console.log(b);
}
Can think of that syntax as 2 parts.
Named function expression
var foo = function bar() {
console.log("b");
}
foo();
bar(); // Will result in Reference Error, cannot reference it by its name.
//Its only accessible within the function itself, like recursion.
Encapsulation using new scope
function exampleWrapper(){
function private() {
console.log("I am private"); -> This function is private
}
private();
}
exampleWrapper();
private(); -> Will not work as its private
//How to expose a function:
function exampleWrapper(){
var i = 10;
function private() {
console.log("I am private"); -> This function is private
}
window.public = function() { -> Attaching it to the global scope
private() -> Still have access to private function
console.log("I am public + "i is" + i++);
}
}
exampleWrapper();
//But their is a problem:
This wrapper function exampleWrapper() has a name and is public.
- Invoking public() -> results in "I am public i is 16"
- Invoking public() -> results in "I am public i is 17"
- Invoking exampleWrapper() results in undefined. (We should not be able to do but we can..)
- then invoking public() -> results in "I am public i is 10" (Not 18, whyy?)
- Whats happening is when we invoke exampleWrapper() a new block of memory is allocated, so variable "i" is initialise again.
//How to solve that? We need to create an IFFE, so the function does not have a name.