JavaScript Notes – 4 (Best Practices)

Posted: February 10th, 2012 | Author: | Filed under: technical | Tags: | Comments Off

In this blog article I want to discuss on few of the JavaScript best practices that I have gleaned from various people, talks, videos, books. For the sources, see here.

VAR, WHERE?

To start with declaration of variables. The best way to do it is

var oneVariable,
    anotherVariable,
    oneArray = [],
    oneObject = {};
// do your thing

Points to notes -
- Good formatting
- Initialization of arrays and object literals without using new is much cheaper (as scope resolution is not required).
- Do not forget the commas after each of the variables

Staying on the topic of variables, there is a useful-to-know concept of hoisting . The following code segment will elucidate the idea-

var foo = 1;
function bar() {
	if (!foo) {
		var foo = 10;
	}
	alert(foo);
}
bar();

Can you guess the output? Click show source below for answer and explanation.

/* the code above re-written to explain 
 * how the interpreter sees it
 */
var foo = 1;
function bar(){
    var foo; // the declaration of foo is hoisted to the top of the scope and undefined
    if(!foo){ // foo is undefined now, this foo not the global variable 
        foo = 10; // set the value of the local variable foo
    }
    alert(foo); // alert foo, the local foo 
}
bar(); // alerts 10

So that is the idea of hoisting explained simplistically. The lesson is to have all your var statements together at the top of the function to avoid such issues. There is something similar that happens with functions too, you can read more about it in Ben Cherry’s article. Long story short, you would want to define your functions before using them.

Do remember that JavaScript has function-level scope, not block level scope . You can create block level scope using anonymous, immediately-executing functions. I will do a more detailed blog post on JavaScript scoping and chaining later.

ARRAYS, LOOPS, YEAH TOGETHER

var a = [];
console.log(typeof a); // "object" Arrays are objects, not arrays. 
console.lo(a.length); // 0

a[10] = "nadu";
console.log(a.length); //11 

a["another_element"] = "another nadu";
console.log(a.another_element); // another_nadu
console.log(a.length); // 11 (still)

This means that arrays are slow, because they are effectively represented as objects. So, the easiest way to improve performance is to NOT do this

var i,
    elements = document.getElementsByTagName("div"); // a huge array
for(i=0; i<elements.length; i++){
    //add a class to the div
    // do something else
}

What is wrong? Well, in each iteration, the length of the elements array is calculated instead just cache the length in a variable and compare it with the loop variable. No big shakes at all right? Well do remember to do this for big arrays!

var i,
    elements = document.getElementsByTagName("div"), // a huge array
    l = elements.length;
for(i=0; i<l; i++){ 
    //add a class to the div
    // do something else
}

DOOM DOM

Few rules for manipulation of the DOM gleaned from this talk.

USE FRAGMENTS TO APPEND NEW ELEMENTS

Assume, you have a container div element and you want to create the child div elements after getting some JSON data from an external server. For appending the child elements,

var i,
    cDiv = document.getElementsById("container-div"), 
    l = jsonResponse.length ;
for(i=0; i<l; i++){ 
    var newChild = document.createElement("div");
    newChild.innerHTML = jsonResponse[i];
    cDiv.appendChild(newChild);    
}

The problem here is that if there are 100 children divs that are going to be created, then the live DOM will be modified 100 times for appending each child div and the performance takes a hit. Instead, the better method is to create a document fragment, append your nodes to the fragment and then attach the fragment to the live DOM.

var i,
    cDiv = document.getElementsById("container-div"), 
    frag = document.createDocumentFragment(),
    l = jsonResponse.length ;
for(i=0; i<l; i++){ 
    var newChild = document.createElement("div"); 
    newChild.innerHTML = jsonResponse[i]; 
    frag.appendChild(newChild);    
}
cDiv.appendChild(frag); // hurray only once do you touch the live DOM

Useful JavaScript Fact – Did you know that you do not need to convert your object keys to strings unless they are a keyword in JavaScript –

var obj = {
    "name" : "Nadu",
    "is_human": true
    "class": "Less Awesome"
}
// instead write 
var obj = {
    name : "Nadu"
    is_human: true
    "class" : "More Awesome"
}


Next planned article on jQuery and its goodness.

Credits

Ben Cherry’s (a Twitter Engineer) blog – http://www.adequatelygood.com
Paul Irish’s talk here


JavaScript Notes – 3 (Pub/Sub)

Posted: January 20th, 2012 | Author: | Filed under: technical | Tags: , | Comments Off

In this blog post I cover the implementation of Publisher-Subscriber (a.k.a Observer) Design Pattern in JavaScript. As the name suggests, the Pub-Sub model is a way by which an entity can publish events/messages and multiple entities can subscribe to those events/messages and subsequently take action. Browser event are examples of this pattern where the browser publishes events like keypress, mouseclick etc. and event handlers in JavaScript can have act when those events occur.
The example explained below can be seen live here. They are from the book JavaScript Patterns
The publisher, say paper which publishes a daily and a monthly magazine and a reader say, joe will be notified when that happens. A publisher object would need the following members for implementing the functionality

subscribers = [] //- an array (list) of all subscribers
subscribe = function(){} //- a method to add to the list of subscribers
unsubscribe = function(){}  //- a method to remove from the list
publish = function(){} //a method to notify all subscribers by calling the methods they provided when they signed up
//All the 3 methods above will need a type parameter as there can be many different type of events

Since these methods are generic to any publisher, it is better to implement this as a separate object. Then we can copy these properties over to any object and convert any object to a publisher (we will see this in a bit).
The code snippet below defines each of the methods and the subscribers array mentioned above.

var publisher = {
    subscribers: {
        any: [] // event type: subscribers
    }, // an object with different event types

    subscribe: function (fn, type) {
        type = type || 'any';
        if (typeof this.subscribers[type] === undefined) {
            this.subscribers[type] = [];
        }
        this.subscribers[type].push(fn);
    },
    unsubscribe: function (fn, type) {
        this.visitSubscribers('unsubscribe', fn, type);
    },
    publish: function (publication, type) {
        this.visitSubscribers('publish', publication, type);
    },
    visitSubscribers: function (action, arg, type) {
        var pubtype = type || 'any',
            subscribers = this.subscribers[pubtype],
            i,
            max = subscribers.length;
            
        for (i = 0; i < max; i += 1) {
            if (action === 'publish') {
                subscribers[i](arg);
            } else {
                if (subscribers[i] === arg) {
                    subscribers.splice(i, 1);
                }
            }
        }
    }
};

Now we have a generic publisher using which we can convert any object to a publisher. The way we do it is that we copy the function properties of the generic publisher to the object. Sweet?

function makePublisher(o) {
    var i;
    for (i in publisher) {
        if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") {
            o[i] = publisher[i];
        }
    }
    o.subscribers = {any: []};
}

Now say we have the paper object which publishes daily and monthly (2 events). So you can have the object as

var paper = {
    daily : function(){
           this.publish("Daily news publication - Breaking News Today");
    }
    monthly : function(){
           this.publish("30 Days of News!", "Monthly Type");
    }
}
// use the makePublisher method to convert this to a publisher object
makePublisher(paper);

Let’s define our subscriber object, joe

var joe = {
    drinkCoffee = function(paper){
               console.log("Reading paper" +paper);
    }
    readMonthlyDigest = function(monthly){
               console.log("Reading monthly digest"+ monthly);                  
    }
}

// Joe subscribers to the paper
paper.subscribe(joe.drinkCoffee);
paper.subscribe(joe.readMonthlyDigest, "Monthly Type");

So effectively the joe object has bound those 2 methods to those 2 events of the paper object. So whenever the paper publishes (monthly or daily), joe’s methods are called since it had subscribed to them.

// Now paper publishes
paper.daily(); // logs Reading paper Daily news publication - Breaking News Today
paper.daily();
paper.daily();
paper.monthly(); // logs Reading monthly digest 30 Days of News!

So, the joe object does not hardcode the paper object or vice-versa. The objects are loosely coupled and one can be changed without impacting the other (adding new subscribers or new publications- weekly)

The beauty of this loosely coupled pattern emerges now when we can turn joe into a publisher and the paper object into a subscriber.

makePublisher(joe);
joe.tweet = function(msg){
    this.publish(msg);
}

paper.readTweets = function(tweet){
    console.log("Someone tweeted on our blog - " + tweet);
}

joe.subscribe(paper.readTweets);
// so joe can say 
joe.tweet("The news was really boring today");

The above was an example of the Pub/Sub model in JavaScript, useful for loosely coupled objects and when you have time to architect your JavaScript solutions before jumping into code directly.


JavaScript Notes – 2

Posted: October 21st, 2011 | Author: | Filed under: technical | Tags: | 1 Comment »

In this blog post, I am introducing Custom Constructor functions, a method for “Classical Inheritance” in JavaScript and Prototypal inheritance in JavaScript. The knowledge in this post is condensed from Stoyan Stefanov’s book JavaScript Patterns.
While trying to understand Prototypal inheritance in JavaScript, I realized that I needed to grasp the above concepts strongly. So hence this post touches upon a breadth of topics.

Custom Constructor Functions

3 ways of creating objects in JS –

var myObject1 = {}; // literal notation
var myObject2 = new Object();
var myObject3 = new MyConstructor(); // custom constructor

The third way is what we are interested in currently. So, it looks the same as we would do in Java to create a new object of a class MyConstructor. Below is one way that the function MyConstructor can be defined. (Do remember that MyConstructor is a function at the end of the day. The capitalized first letter is a coding practice to differentiate custom constructors from functions)

var MyConstructor = function(name){ 
    this.name = name;
    this.hello = function () {return "Hello "+this.name;};
}
var obj = new MyConstructor("nadu");

When we call MyConstructor with new, 3 things happen inside the function

  • An empty object is created and referenced by this variable, inheriting the prototype of the function.
  • Properties and methods are added to the object referenced by this.
  • The newly created object referenced by this is returned at the end implicitly (if no other object was returned explicitly).

In the above example, the hello was added to this. So each time new MyConstructor gets called, a new function hello is created in memory. Since the method hello does not change from one instance to another, we can add that to the prototype of MyConstructor.

MyConstructor.prototype.hello = function(){
    return "Hello "+ this.name;
}

A prototype is an object and every function you create automatically gets a prototype property that points to a new blank object. You can add functions to the prototype and they will be accessible to all the objects created using new MyConstructor()

There are 2 different ways inheritance (code-reuse) can be done in JavaScript. One is to create classes to emulate the typical (class-ical) inheritance and the other is using the prototypal nature of the language.

Classical Inheritance

This can be implemented in JavaScript based on custom constructors. Below is just one pattern (simplest) of implementing classical inheritance. Refer to the book for different implementations.

// parent constructor
function Parent(name){
   this.name = name || "Adam";
}
// add functionality to the prototype
Parent.prototype.say= function(){
    return "Hello "+ this.name;
}

The hidden link __proto__ points to the prototype property of the constructor function that created that object.

//child constructor
function Child(){}

//inherit - C will have access to P's properties
inherit(Child,Parent);

var kid = new Child();
console.log(kid.name);//"Adam"
console.log(kid.say()); 

// here is how inherit is defined
function inherit(C,P){
    C.prototype = new P();
}

Working Example on JS Fiddle

Prototypal Inheritance

In Prototypal inheritance, objects inherit from objects. You have an object that you would like to reuse and you want to create a second object that gets functionality from the first one.

var parent = {
    name:"Parent"
};

// the new object which inherits parent
var child = object(parent); 

console.log(child.name); // Parent
console.log(child.prototype);
console.log(child.__proto__);


// here is how object is defined
function object(o){
    function F(){};
    F.prototype = o;
    return new F();
}

An important thing to understand is that the child.__proto__ points to the parent object. The __proto__ link points to the prototype property of its parent constructor which was the temporary function F. The __proto__ link is what makes the interpreter check for the property name in its parent.

The console output showing the values of child.name, child.prototype, child.__proto__


JavaScript Closure Example

Posted: September 2nd, 2011 | Author: | Filed under: Uncategorized | Tags: , | Comments Off

It has taken me time to fully understand the concept of closures in JavaScript. Here is an example of code that I rewrote so that we can use closures and get the thing to work the way we actually want it to.

The situation:
We have a set of buttons and we have to attach on-click handlers to them. These handlers should be called with parameters that are button dependent i.e., the innerHTML of the text box next to that particular button or say we need some attribute of the button (data-value, or some custom attribute).

We want to attach a function inviteUserToGroup with the specific parameters as event handlers to all the buttons.
So we initially wrote :

//add event handlers to invite buttons
var inviteBtns = $$('.inviteBtn'); //Prototype to get an array of elements with this class name
var len = inviteBtns.length;
var i;
var groupIdForUser;
var detailsForUserInGroupName;

for(i=0;i<len;i++){
    groupId = $('groupIdForUser'+i).innerHTML;
    details = $('detailsForUserInGroupName'+i).innerHTML;
    //Protoype syntax to attach event handlers 
    //Event.observe(element,event,handler)
    Event.observe(inviteBtns[i],'click',function(){
        inviteUserToGroup(groupId,i,details);});
}

function inviteUserToGroup(a,b,c,d){ doSomething();}

So, we attach inviteUserToGroup method with the parameters. Since we enclosed the handler as a function, one can assume that due to the scope of the function, it should work fine and the event handler will be called with the correct parameters. That doesn’t work that way. All the event handlers get called with the value of i = len. You thought closures would work here, but it does not.
So what do you do? Create a real closure. The following code does that

/* DOES NOT WORK
Event.observe(inviteBtns[i],'click',function(){
    inviteUserToGroup(groupId,i,details);});
*/

Event.observe(inviteBtns[i],'click', 
    (function(gId,i,dtls){
        return function(){
                   inviteUserToGroup(gId,i,dtls);
               }
        })(groupId,i,details)));

So what is happening?
1) Create an immediate anonymous function which takes in the parameters that you want in your handler.
2) In the anonymous function return the actual function with parameters that you want to call. In this case we return inviteUserToGroup() with the parameters.
The important point to understand is that, the immediate function will execute and hence have the current values of groupId, details and i, which are passed to it. Due to the closure, the inner function (which is returned) has access to these values even after anonymous function has completed execution. So, inviteUserToGroup is attached to each button with the correct parameters.

For completion, another way of doing this is

Event.observe(inviteBtns[i],'click',
    'inviteUserToGroup('+groupId+','+i+',\''+details)');});

Not recommended by many people as this uses the eval function to evaluate the JavaScript inside the quotes.

Is there a better (maybe more legible) way of doing this? Let me know!


JavaScript Notes – 1

Posted: August 19th, 2011 | Author: | Filed under: technical | Tags: , | Comments Off

My notes on JavaScript Patterns. This is just a part of the patterns covered by Addy Osmani and those covered by Stoyan Stefanov

**Disclaimer**: The code examples below are modified examples from JavaScript Patterns

Namespaces
Using global variables and functions in JavaScript can lead to smashing of variables as the code base grows. So a simple way of handling namespaces is

var NxJ = {};
NxJ.property1 = "Name is Nadu";
NxJ.method1 = function(){console.log("name is bond, james bond");}

// if you want to add modules
NxJ.modules.module1 = {};
NxJ.modules.module1.data = {"a":1,"b":2};

var moduleToBeUsed = NxJ.namespace("NxJ.module1.module2.module_n");

The variable names keep getting larger and larger. A way to handle this is to create a function called namespace, that can parse the module name and return only that module with all the methods. Useful when you are using big libraries like YUI (they have different modules for DOM, Events etc)

Private properties, Module and Revealing Module
By default everything is public

var myObj = {
	myName : “Nadu”;
	getName = function(){
		return myName;
	}
};
console.log(myObj.myName); // accessible

So a way of fixing this is

myObj = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	return: // yes return an object
	{
            getName = function(){
               return myName;
            }
	};
}());

console.log(myObj.myName); // inaccessible now
console.log(myObj.getName()); // this is the right way to get it

Points to note -

  • Immediate function call – so what value does myObj get?
  • var before myName makes it private because of closure
  • getName is a privileged function

Lets add namespaces now,

var NxJ = {};
NxJ.coolModule  = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	var yourName = “Someone else”;

	return:
	{
              getName = function(){
		   return myName;
	      },
	      setName = function(n){
			myName = n;
              }
	};
}());

So that’s the Module pattern!
Since we have reached alive till here, we will jump to the Revealing module pattern, which is nothing but a simple extension of the Module pattern.
In the Revealing module pattern, you define all the properties as private in the object and then return only those that you want to be made public

var NxJ = {};
NxJ.coolModule  = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	var yourName = “Someone else”;
        var getName = function(){return(myName);};
	var setName = function(n){ myName = n;}

	return:
	{
		getName: getName,
		getTheAwesomeName: getName // sort of an alias!
	};
}());
console.log(NxJ.coolModule.getName());
console.log(NxJ.coolModule.getAwesomeName()); // this works too

There are 2 advantages of this pattern, one is that it’s a little more cleaner than the Module pattern and two you can have these aliases. One can create a JavaScript API and then just return all that is public.

Be careful!

var NxJ = {};
NxJ.coolModule  = ( function(){
    // a var before myName - makes it private 
    var student = {"name":"Nadu", "age":"18-till-i-die"};
    var getStudent = function(){ return student; }    
    
    return    {
        getStudent: getStudent
    };
}());
var stud = NxJ.coolModule.getStudent();
console.log(NxJ.coolModule.student); // not possible
console.log(stud.name); // says Nadu
stud.name = "Narayanan Ramakrishnan"; // trying to modify it
var stud2 = NxJ.coolModule.getStudent();
console.log(stud2.name); // prints Narayanan Ramakrishnan - Hey WTF ?

This is because for arrays and objects, JavaScript returns the reference, so its accessible to anyone who has the reference. So one way of handling this is to return a new object that has properties that the caller is interested in. Called the Principle of Least Authority which states that you should never give more than intended. One way of doing this in the example above is, instead of giving the caller everything, you can break it down into functions getName(), getAge(). There is another approach using a general purpose cloning function, but that will be covered later.

More notes to follow in another post.
Further reading
A beautiful explanation of Module Pattern by Twitter engineer Ben Cherry
Signing off treat – www.jsfiddle.net