DEV Community

Nikunj R. Prajapati
Nikunj R. Prajapati

Posted on

3 3

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay