Showing posts with label AdvancedIIFE. Show all posts
Showing posts with label AdvancedIIFE. Show all posts

Wednesday, April 18, 2018

IIFE explanation with closure

Simple example for IIFE with closure explanation:


var MyClosureTest = (function (){
  var WelcomeMessage = 'Welcome to IIFE with Closure example';
  return {
    getWelcomeMessage: function () { return WelcomeMessage;},
    setWelcomeMessage: function (message) { WelcomeMessage = message}
  }
}());


Explanation:

Here,  We are not assigning a function to MyClosureTest. We want the result of invoking that function to MyClosureTest.

Important is, see at end - we added () in the last line.(IIFE).

If I want to get the WelcomeMessage then I can use getWelcomeMessage and it will work.  The below line will print our message.


console.log(MyClosureTest.getWelcomeMessage()); //Welcome to IIFE with Closure example

But following way would not work:


console.log(MyClosureTest.WelcomeMessage); 
// undefined

But you can set an get the expected message result:


MyClosureTest.setWelcomeMessage('I understood IIFE and closure');
console.log(MyClosureTest.getWelcomeMessage()); 
//I understood IIFE and closure






Self Invoking function | Immediately Invoked Function Expressions

Remember the below , this is the simple and best example for IIFE (Immediately Invoked Function Expressions).


(function () {
  // body of the function
}());

An another way for IIFE


(function () {
  // body
})();


It will be invoked automatically without being called. You must add parentheses(based on above two - I prefer second one ) in starting of the function and end of the function to express that it is a function expression.

How it is work ?

At the end we have added (), this is the reason its calling automatically. So remember adding () this at end is must. So that IIFE will work for you.

Why do we want to use this?

Most of the time for the below two reasons, we are using IIFE.

1. For Better namespace management

2. Closures

Next chapter we can see a good example about closures with IIFE.