Monday, June 18, 2012

JavaScript Closure : “A state of being closed”

This is another fun and interesting aspect in JavaScript programming. Closures are powerful because they enable inner functions to retain access to an outer function's variables even after the outer function has returned. Let’s try to understand it in a fun way.

JavaScript Closure: Analogy

A King has lots of GOLD which he has kept in a secret treasure. There is a map which leads to treasure but its only King who knows about it. King decides that only after his death prince should get map which should lead prince to the Treasure of GOLD. King in which case is an outer function which gives life to inner function but makes sure that after its execution has ended inner function which is prince has access to treasure. Lets take a look at following code and represent it in technology way:

            var King = (function(){
                     var treasureMap = 'Map to treasure';
                     this.myPrince = function(){
                            alert(treasureMap);
                     }
                     return {
                            prince:this.myPrince
                    }         
             })();

In  above code King is class and has private variable treasureMap which is not exposed because the function has been executed as soon as it is defined (module pattern). Lets see if King has treasureMap:

                        alert(King.treasureMap); // Oops it comes as undefined 


which means king may have it but is not revealing it which fulfills our use case.

King left prince as successor, it will be interesting to see if prince knows about it or not because King is dead and cannot access treasureMap.

                        King.prince(); // Alerts 'Map to treasure' Hurray!

How this happened? Closure is the answer. King.prince is the inner function in King which knows about treasureMap and has access to it even though King has left the world. This is closure which enabled prince to retain King's treasureMap property even when King has returned from execution call.


Closure: Memory Leaks

Like any other good thing, closure comes with challenges too. As long as closures are active, this memory cannot be garbage collected. Therefore, closures can lead to memory leaks if not used well. Lets examine a use case where it can lead to memory leak. Most of the memory leak in JavaScript is due to circular reference between javascript object and DOM element. For e.g.

               <html>
               <body>
               <script type="text/javascript">
                              window.onload=function preProcess(){
                               var obj = document.getElementById("elId");
                               obj.onclick=function createLeak(){
                                              //Some processing
                                              alert("Adding leak");
                               };
                               obj.something=new Array(1000);
                              
               };
               </script>
               <button id=" elId ">Test Me</button>
               </body>
               </html>

In the above example on load of window function preProcess will  be executed which will create a new JavaScript object obj with reference to DOM element elId and the DOM element has reference to JavaScript object thereby creating a circular reference. It is important to break this circular reference in order to address memory leak from the code. Simplest way to achieve this is to set JavScript obj to null when that object is no more required.

               <html>
               <body>
               <script type="text/javascript">
                              window.onload=function preProcess(){
                               var obj = document.getElementById("elId");
                               obj.onclick=function  createLeak (){
                                              //Some processing
                                              alert("no leak");
                               };
                               obj.something=new Array(1000);
                               obj = null; // set the object to null to break circular reference
                              
               };
               </script>
               <button id=" elId">Test Me</button>
               </body>
               </html>

Server side programming in JavaScript with nodejs, expressjs, stylus, jade etc. makes efficient use of closure. In conclusion, a closure in JavaScript is like keeping a copy of the all local variables, just as they were when a function exited.

Tuesday, June 12, 2012

ExtJs || jQuery || YUI

When I meet people they ask me which is good; ExtJS or jQuery or YUI or may be Dojo and this is what I feel and say. Over past few years I have worked with some of these libraries with more extensively on ExtJS and YUI (with yui-ext, does that rings a bell ☺?).


I like it. Solves the purpose!
It is very well crafted Object Oriented JavaScript library for Rich Internet Applications. It is beautiful to write classes, extend them, override methods, create objects, and encapsulate objects in JavaScript with ExtJS. It is like working with any other OOP language like, where one can use extend and understand what that means. Out-of-box  collection of component or widgets are efficient and extensible. Wonderful layouts makes the job easy for developer like card layout, border layout etc. Store makes the job easy to store data in data-structure which has rich API for query etc. Components like grids, tabbed panels, form, tree etc. are customizable and extendable and makes ExtJS even more attractive. Good community contributing to plugin development. Good documentation with implementation examples. 

It is not open source. I feel it is good for applications where there is not a whole lot of business logic happening on the client and there is less frequent DOM manipulation. It is thick on client with the amount of code it has. Until ExtJS 4 the architecture doesn’t really follow the MVC pattern, the view is either encapsulating the model or tightly coupled to model.

It is a good RIA JavaScript library and has lot into it.

Smart & Intelligent!
jQuery is one of most widely used and popular JavaScript framework in web application development. It is very thin on client. It has extensive API for DOM manipulation. It has huge community support which is contributing to jQuery and making it more rich. UI components are usually extensible and can be customized as per use. If I have web application which requires AJAX and UI tweaks then jQuery is one good solution. Documentation is good and it has ease of learning. It is very to use and integrate into existing project.

UI components are limited but there are plugin from the community. Plugins can be unstable depending on their quality. Complex UI components are not part of jQuery. Plugins might require more work to make it work with the application.



Cool!
YUI has evolved over the period of time. I have worked with YUI 1.6 with yui-ext which was extension of YUI with lots of other features. Out of box components set is rich and can be used with existing application. It was one of the first to let access to their library over the web. Documentation is extensive and it has good set of examples. It is backed up by yahoo and they have used it most or all of Yahoo’s web applications which make a good point for YUI.

YUI lacked good syntax for JavaScript. It took time to evolve through the generations of JavaScript libraries. YUI led to foundation of other libraries but could not develop the similar momentum for itself.

Now to answer the big question “Which one to use for my application”? Answer is very simple:  It depends on the application and what that application intent to do, if the application is to give RIA feeling, less data intensive on client, faster development and funding is enough to buy a rich library go for ExtJS. If price is crunch and library has to be open source and should be extensive on client DOM manipulation then jQuery is very good solution. KnockoutjsBackbone.js and many other libraries have either plugins or extensions with jQuery. YUI is also good for such applications but one lacks community and it is good for converting parts of web application into RIA easily.

No matter what I like all three of them and I feel if one implement them well they all solve the purpose.



Monday, June 11, 2012

Why blogging?



I don't know how to blog or shall I be honest and say I don't how to write good blog which interests you. I will do something which will help me bring out what is "inside me". I am excited when I am writing this first blog. I don't want my blogs to be boring and too monotonous, I will try if we can have fun together.

Here is what I feel which is making me blog:
  • I am focused on software engineering, Agile, Scrum, fitness and family.
  • There are three ingredients in good life: learning, earning and yearning.
  • I feel I can spread what I have learnt so far in my life which might benefit you.
  • I feel it is my way of communicating and letting you know what I am and what I can be.
Life is small so live it to the fullest. For those who know me understand what I meant by that, if not come over and I will make it happen.

I am all excited and hopeful that I continue this and make it interesting for both of us.