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

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.

@MappedSuperclass vs. @Inheritance

MappedSuperClass must be used to inherit properties, associations, and methods. Entity inheritance must be used when you have an entity, and several sub-entities. You can tell if you need one or the other by answering this questions: is there some other entity in the model which could have an association with the base class? If yes, then the base class is in fact an entity, and you should use entity inheritance. If no, then the base class is in fact a class that contains attributes and methods that are common to several unrelated entities, and you should use a mapped superclass. For example: You can have several kinds of messages: SMS messages, email messages, or phone messages. And a person has a list of messages. You can also have a reminder linked to a message, regardless of the kind of message. In this case, Message is clearly an entity, and entity inheritance must be used. All your domain objects could have a creation date, modification date and ID, and you could thus

Hashmap Keyset and EntrySet difference.

If you're concerned about performance when iterating through your hash map, I suggest you have a look at  LinkedHashMap . From the docs: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity. HashMap.entrySet() The source-code for this implementation is available. The implementation basically just returns a new  HashMap.EntrySet . A class which looks like this: private final class EntrySet extends AbstractSet < Map . Entry < K , V >> { public Iterator < Map . Entry < K , V >> iterator () { return newEntryIterator (); // returns a HashIterator... } // ... } and a  HashIterator  looks like private abstract class HashIterator < E > implements Iterator < E > { Entry < K , V > next ; // next entry to ret