[JS] IIFE (Immediately Invoked Function Expression)
IIFE (Immediately Invoked Function Expression) in JavaScript runs immediately when it defined.
const firstIIFE = (function () {
var score = Math.random() * 10;
console.log("First: ", score >= 5);
})();
// Normal Function
function notIIFE() {
var score = Math.random() * 10;
console.log("Second: ", score >= 5);
}
notIIFE();
// It is possible to pass paramester when it executed
(function secondIIFE(luckynum) {
var score = Math.random() * 10;
console.log("Second: ", score >= 5 - luckynum);
})(5);
notIIFE();
console.log(firstIIFE); // undefined
You can use this feature to make private/public variables and methos in it.
const test_module = (function() {
const p_value = "Access";
const privateFunction = function() {
console.log(p_value);
}
return {
publicFunction : function() {
console.log("This is a public function: ", p_value);
}
}
})();
test_module.publicFunction();
test_module.privateFunction(); // Not function
Comments