An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
August 19, 2020 09:26 am GMT
Original Link: https://dev.to/a_vietnamese_guy/what-are-immediately-invoked-function-expressions-iifes-15mi
What are immediately invoked function expressions (IIFEs) ?
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 0console.log(counter.getNum());counter.inc(); // num is 1counter.inc(); // num is 2counter.inc(); // num is 3// this technique gives you the ability to hide // state inside the function closureconsole.log(counter.getNum());
Reference book:
Programming Javascript applications of Eric Elliot
Original Link: https://dev.to/a_vietnamese_guy/what-are-immediately-invoked-function-expressions-iifes-15mi
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To