In Javascript it is possible for a function to call itself when it is defined. This technique is called immediately invoked function expression (abbreviated IIFE), though it sounds like the definition of recursion but its main purpose is to encapsulate modules (this was a popular technique before ES6).
See the below example to have a better understanding
var counter = (function () {
var num = 0;
function increaseNumber() {
num++;
}
function decreaseNumber() {
num--;
}
return {
getNum: function () {
return num;
},
inc: increaseNumber,
dec: decreaseNumber,
};
})();
// the inital value of num is 0
console.log(counter.getNum());
counter.inc(); // num is 1
counter.inc(); // num is 2
counter.inc(); // num is 3
// this technique gives you the ability to hide
// state inside the function closure
console.log(counter.getNum());
Reference book:
Programming Javascript applications of Eric Elliot
Top comments (0)