-
Immediately Invoked Function Expression
IIFE
(function () {
/* ... */
})();
Arrow function
(() => {
/* ... */
})();
Async
(async () => {
/* ... */
})();
- This also called as self executing anonymous function
Let's understand this in 2 parts
(
// This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
let a = 10; // will be discarded after the function is executed.
)() => immediately invoked function
Example
// "counter" is a function that returns an object with properties, which in this case are functions.
let counter = (function () {
let i = 0;
return {
get: function () {
return i;
},
set: function (val) {
i = val;
return `value ${i} set successfully`
},
increment: function () {
return ++i;
}
};
})();
// Just to log data
const log = (f) => console.log(f);
// These calls access the function properties returned by "counter".
log(counter.get()) // 0
log(counter.set(3)) // "value 3 set successfully"
log(counter.increment()) // 4
log(counter.increment()) // 5
log(counter.i) // accessing private variables undefined.
Top comments (0)