Introduction:
As we all aware of Java script framework to develop a web application. It provides lot of flexibility to achieve the user experience and to improve the website performance. In this article we will dig into the one of the feature is JavaScript – Immediately-invoked function expression (IIFE).
Basic Requirement:
To go over this article, one should aware of Java script framework and it’s basic functions.
Starting Point:
To understand IIFE, we should know why we should use. Basically it comes to Java script, in big projects like ASP.NET MVC application – maintaining java script code difficult.
I went over lot of web project, the code of java script will be messed with view part of the project. Which is not able to understand and it’s not able read also.
In this article, I will show you very small sample or example, how to implement an IIFE in you project. Let’s start.
I’m assuming that, you have already a web project where Java script is not modularized. So I will take you step by step wise on the same concept.
Step 1: Add a new folder app under scripts folder of your project and Add new Java script file name it as app.js. Add a function with meaningful name. I will add here InitGigs(). I shown first step in Image 2.
Image – 1: InitGigs function in app.js.
Step 2 : Paste your javascript code into initGigs from any view and call InitGibgs Function into the main view. I shown in Image 2.
NOTE: After doing this you add new js files to bundle.config file,in case you using ASP.NET MVC project.
Image – 2: Pasting javascript code to IntiGigs()
– With step 1 and step 2 we looking to resolve the complexity of java script but we not using the IIFE concept. Basically the function InitGigs placed in a global namespace, we may get same function name of method as application grows, it will pollute the application. So we will use the IIFE concept.
Step 3 : In short I will shown an implementation of the IIFE in the image – 3. Here I have create variable GigsController and function will be invoked automatically.
I have declared a method in GigsController with the name init and it will not accessible from outside of this. I mean it’s like a private field as like in C#. I returning a key with init which intern returns init method. What ever we will add in return section will act as public.
Image – 3: Implementation of IFEE in brief.
Step 4: With implementation, I moved all code from InitGibgs to Init function. So I can access the method like GibgsController.Init(). Which will initialize the function.
Advantages of IIFE:
1. Avoids global declared duplicate function (names).
2. Java script code smell reduces.
3. Application maintains will be easy.
Conclusion: IIFE in java script it good concept and it’s easy to implement in web application. I tried to explain it in easy way. You can refer Wikipedia link I mentioned here for more examples. Thanks.
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
Happy coding 🙂