Skip to main content

Playing around with IIFEs (Iffys)

So heres my take on the IIFE.

We will first begin with understanding what really is IIFE, some simple examples of IIFE and what are the benefits it provides to a Javascript developer (Us!!!). Then we will look into some more advanced topics related to IIFE.


What is IIFE?

IIFE is Immediately Invoked Function Expression. In simple words these are the functions which are called immediately once they have declared. Commonly they are written like this:

1:  (function () { // open IIFE  
2:    console.log("inside IIFE")  
3:  }()); // close IIFE  

This code, when executed will print "inside IIFE". Kindly note the syntax. The trailing parenthesis are the ones which do the magic of invoking this function immediately. If we remove the trailing parenthesis, then this code becomes just a normal function definition and nothing else.

Also, dont miss the trailing semicolon, its required. Missing the trailing semicolon could cause some serious problems. For e.g. conside this piece of code

1:  (function () {  
2:    console.log("first iffe");  
3:  }()) // no semicolon  
4:  (function () {  
5:    console.log("second iife");  
6:  }());  

If you try to execute the above piece of code, you will get the below error in console.

1:  Uncaught TypeError: (intermediate value)(...) is not a function  

The above code is interpreted as the first IIFE is the function which has to be called and the second IIFE is the parameter which is to be passed to it. To solve this confusion, all you need to do is add a semicolon after the first IIFE.

IIFE Applications

1. Introducing a new scope:

You typically introduce a new scope to restrict the lifetime of a variable. One example where you may want to do so is the “then” part of an if statement: it is executed only if the condition holds; and if it exclusively uses helper variables, we don’t want them to “leak out” into the surrounding scope.

1:  function f() {  
2:    if (condition) {  
3:      var tmp = ...;  
4:      ...  
5:    }  
6:    // tmp still exists here  
7:    // => not what we want  
8:  }  

If you want to introduce a new scope for the then block, you can define a function and immediately invoke it. This is a workaround, a simulation of block scoping:

1:  function f() {  
2:    if (condition) {  
3:      (function () { // open block  
4:        var tmp = ...;  
5:        ...  
6:      }()); // close block  
7:    }  
8:  }  

2. Hiding variables from Global scope:

Global variables have two disadvantages. First, pieces of software that rely on global variables are subject to side effects; they are less robust, behave less predictably, and are less reusable.
Second, all of the JavaScript on a web page shares the same global variables: your code, built-ins, analytic code, social media buttons, and so on. That means that name clashes can become a problem. That is why it is best to hide as many variables from the global scope as possible. For example, don’t do this:

1:  <!-- Don’t do this -->  
2:  <script>
3:    // Global scope  
4:    var tmp = generateData();  
5:    processData(tmp);  
6:    persistData(tmp);  
7:  </script>

The variable tmp becomes global, because its declaration is executed in global scope. But it is only used locally. Hence, we can use an IIFE to hide it inside a nested scope:

1:  <script>  
2:    (function () { // open IIFE  
3:      // Local scope  
4:      var tmp = generateData();  
5:      processData(tmp);  
6:      persistData(tmp);  
7:    }()); // close IIFE  
8:  </script>  

Note: There is a module pattern which can also solve this problem. We will study module pattern in subsequent blogs.


Comments

Popular posts from this blog

Patterns Knowledge

Anti Pattern: Its a pattern which we repeatedly do and which brings negative results. Architecture by implication: Systems lacking a clear and document architecture. Cover Your Assets: Continuing to document and present alternatives, without ever making an architectural decision. Witches Brew: Architectures made by groups resulting in a mix of ideas and lack a clear vision. Gold Plating: Continuing to define an architecture well pass the time which results in no benefits to the architecture. Vendor King: A product dependent architectures leading to a loss of control of architecture and development costs Big Bang Architecture: Designing the entire architecture at the beginning of the project when you know the least about the system.

Some good links

https://www.html5rocks.com/en/tutorials/internals/howbrowserswork/ http://taligarsiel.com/ClientSidePerformance.html -- Client side performance tips https://ariya.io/ https://vertx.io/docs/ -- New exciting Framework, Must read. https://javaee.github.io/ -- Very good resource to see various javaee projects and explore enterprise architecture and design concepts. https://projects.eclipse.org/projects/ee4j -- Lots of interesting open source projects by eclipse http://openjdk.java.net/projects/mlvm/ -- the main project for supporting more dynamic languages to jvm. http://esprima.org/ -- EcmaScript parser http://c2.com/ppr/ and http://hillside.net/ -- Good place to learn patterns http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf https://validator.w3.org/nu/ -- This will validate your website css and js https://www.cellstream.com/intranet/reference-reading/faq/216-what-is-2-128.html http://shattered.io/ -- An example of SHA1 collision attack.

Cryptography

Crypto - Secret Graphy - To Write CryptoLogy - The science of secrets Symmetric Cryptography: Both the parties have the same keys. Asymmetric Cryptography: Both the parties do not have the same keys. They work on the concept of Public and Private Keys. Its also called as Public Key Cryptography. Its very expensive to encrypt and decrypt using Asymmetric Cryptography. Hence there are systems which use both Symmetric and Asymmetric Cryptography together like ECC. Don't implement your own Crypto. Its very easy to do it incorrectly. Side Channel: When you can observer properties of a function other than their functional behaviour it is called as Side Channel. E.g. Knowing how long it takes to encrypt a text, knowing the length of a particular encrypted text. In cryptography,  Kerckhoffs's principle  (also called  Kerckhoffs's  desideratum, assumption, axiom, doctrine or law) was stated by Netherlands born cryptographer Auguste  Kerckhoffs  in the 19th century: A c