DEV Community

Nikunj R. Prajapati
Nikunj R. Prajapati

Posted on

Day 3 : What Is IIFE in Javascript ?

  • Immediately Invoked Function Expression
IIFE
(function () {
  /* ... */
})();

Arrow function
(() => {
  /* ... */
})();

Async
(async () => {
  /* ... */
})();

Enter fullscreen mode Exit fullscreen mode
  • 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

Enter fullscreen mode Exit fullscreen mode

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. 

Enter fullscreen mode Exit fullscreen mode

Top comments (0)