Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 19, 2020 09:26 am GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To