Wednesday, March 28, 2012

JavaScript Function Spaghetti Code

In this post we will have a look at the spaghetti code created by functions and how to avoid them. First lets quickly go through why this is a cause of concern.

Problems with Function Spaghetti Code

  • Variables/ functions are added to the global scope

  • The code is not modular

  • There's potential for duplicate function names

  • Difficult to maintain

  • No namespace sense.

Let's take for example the following set of functions and check whats the issue with them.
// file1.js

function saveState(obj) {
    // write code here to saveState of some object
    alert('file1 saveState');

// file2.js (remote team or some third party scripts)
function saveState(obj, obj2) {
     // further code...
    alert('file2 saveState");

Now the problem here is if your application is using saveState() then the execution of saveState() which one to call is determined by the script loading.  The later script overrides same functions already defined by earlier script.
For e.g.

If this script is references as
<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

Then the function defined in file2.js will be overriding the one defined in file1.js. If you change the order the order of overriding changes. So, you can see this is a cause of concern if you have a n application which depends of javascripts both internal and from third party. One way to solve this problem is with closures.

Closure inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. ~ Douglas Crockford
In JavaScript yo can nest function and the nested function has access to all the variables and functions defined by its parent. This seems very simple and straightforward, but this is a very complex concept under the hood. Its like a function still holds the variables around its environment even after the function seems out of scope. Let us quickly go through an example.

// The getDate() function returns a nested function which refers the 'date' variable defined 
// by outer function getDate()
function getDate() {
   var date = new Date();    // This variable stays around even after function returns

   // nested function
   return function () {
      return date.getMilliseconds();

Now if you call this function as shown below, you will see that the inner function holds on 
the the date variable.

// Once getDate() is executed the variable date should be out of scope and it is, but since 
// the inner function
// referenes date, this value is available to the inner function.
var dt = getDate();


The output of the above alert will be the same value of date.getMilliseconds();

Let's take another look at closure and use a module kind of pattern..

var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();

var dt = new MyDate();

alert(dt.getMilliSeconds());  // This will throw error as getMilliSeconds is not accessible.

Make the following changes
var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();
    return {
        getMs : getMilliSeconds

What you are doing above is encapsulating all your logic in a namespace, in this case MyDate, and only
returning public methods to the outside world as an object literal.

You can use this as shown below..

var dt = new MyDate();
alert(dt.getMs());  // This should work.

The above construct is very similar to "The Revealing Module Pattern", which we will cover in
subsequent posts.

Now let's solve the original problem of saveState.

function App() {
    var save = function (o) {
        // write code to save state here..
        // you have acces to 'o' here...
    return {
        saveState: save

var app = new App();

app.saveState({ name: "rajesh"});

Your application can use this as follows, without worrying about other saveStates floating around...

var app = new App();
app.saveState({ name: "rajesh"});

To conclude, we had look at why function spaghetti coding is bad and how to avoid this by using closure and module pattern.

In subsequent post we will look at how to create namespace and dig into deeper of the module pattern.

Hopefully you will find this useful.

Friday, March 23, 2012

JavaScript - The this keyword

"this" is one of the most misunderstood construct in JavaScript.  To understand this first lets go through how to create a construction function in JavaScript.  A constructor function is a function which is used to create instances of objects in JavaScript.

You define a constructor function using the same notation that you use to define a normal JavaScript function.  The convention to follow is to capitalize the first letter of the function name.

This requirement is not enforced by the JavaScript language but it is a generally accepted practice and there are many benefits which we will shortly discuss.

Let's define a constructor function to hold our menu information.

function Menu() {


So, in the above snippet you have a constructor function named Menu defined. At present this function doesn't do anything good.

Let's see how to invoke this function

var menu = new Menu();

Let's add some public properties to this function.
function Menu() {
    this.menuName = "File";

Let's create an instance and see how we can use this.

var menu = new Menu();

If you run the above code, you should get an alert with a value "File".  This is not so interesting.

Let's pass, in the name information to the function.

function Menu (name) {
    this.menuName = name;

Now you can call this function as shown below.

var menu = new Menu("file");
alert (menu.menuName);  // You will still get an alert with a value 'file'

Isn't this interesting now.   Now the point to remember is that nothing in JavaScript prevents you from invoking this function directly.

For e.g.

var menu = Menu("file");

What do you think the output of the above will be if you do an

You will get an error similar to "Uncaught TypeError: Cannot read property 'menuName' of undefined".

You can see this in action here

Why?  Any idea?  Also, there is a side effect to this.   You accidentally created a global variable "menuName".

You don't believe me.  Try doing an

alert(menuName);   // OR

Ok. Lets get a bit deeper into how this thing work.  By default a constructor functions always returns an instance of the function object  on which the "new" is called upon.

If you directly invoke a constructor function without creating a new instance, then that function is executed rather than an object being constructed. So, the return value of that function invocation will be undefined as you are not explicitly returning any value from the function.

So, all assignment to "this". goes to the global window object and you accidentally create globals.
Always name your constructor function starting with an uppercase.
The primary reason why this is an issue is because JavaScript don't force you to construct object of constructor function as for JavaScript execution engine there is no difference between the two.

This is where naming convention plays an important role. Name all your constructor function starting with an uppercase letter. This way it will be very easy for you to detect if there is any unintentional misuse of the constructor function. Besides there are certain tools like "jslint" which warns you if you directly invoke a constructor function which has a name starting with uppercase.

Ok, so how to avoid this problem.  What we want is whenever the user uses the Menu function either as direct function call or as a constructor function we need the function to return a menu object to the user.

A simple solution is to return an anonymous object from the constructor function with required properties attached to it.

function Menu(name) {
    return {
        menuName : name

We can use this function either by direct call, or through constructor invocation, we will always get the correct object, without creating globals.

Why this works is because constructor function by default returns the instance of the object on which it is invoked.  The other interesting thing is we can return any thing from this constructor function.  We will use this feature to return correct object back to the caller.

var menu = Menu("file");  / called directly
alert(menu.menuName);  // alerts 'file'

var menu1 = new Menu("Help");  // call with new
alert(menu1.menuName); // alerts 'Help'

// alert(menuName);  // See no, globals

this Gets tricky

Take this example below. We have a simple function which returns stock quote. Pretty simple example in this case.

function StockQuote() {
    this.quote= "12,13,343,343";
    this.getQuote= function() {
         //this is expected to be a reference to the current instance
         return this.quote; 

Now lets' say we need to get the quote in the next 3 seconds..

var quote = new StockQuote();
// call the getQuote function in 3 seconds.
setTimeout(quote.getQuote, 3000);

Many beginner JS dev may think this may work, but it won't. It'll give an error saying that quote is undefined. This is because there is no binding of functions to instances in JavaScript. Whenever the instance isn't explicitly stated, then "this" becomes windows object (at least in the browser, as js runs in other environment as well). Writing quote.getQuote() indicates that you want "this" to belong to quote, so it will work correctly. However, the setTimeout function only has a reference to that function. When it calls it, after 3 seconds, it is not aware of "quote", so JavaScript sets this to window.

"Fixing" this

There are several ways of forcing this to be what you intend to be and many of them uses some unique features of JavaScript.

The two important ones are
  • apply

  • call

apply is a member of every function. It says "invoke this function on this object (change the context of the object).

An example is shown below.

// These two are same..
// "quote" is the this context you are passing

// you can also do this.
var myQuote = new Quote();

// The above line does the same thing as

Before solving the setTimeout problem lets briefly have a discussion on Lexical Scroping in JavaScript.

Lexical scoping allows you to access local variables in a parent function by the child functions. i.e. if a function is defined withing another function, it can access its own local variables as well as those of the function it was defined within.

Now let's solve the setTimeout problem with Lexical scoping.

var myQuote = new Quote();
setTimeout( function() {
}, 3000);

We created a new anonymous function which we are passing to the setTimeout. Our new function can access myQuote, so it just applies it to the getQuote function.

Solving setTimeout problem using "apply".

var myQuote = new Quote();
setTimeout(myQuote.getQuote.apply(myQuote), 3000);

The difference between call and apply is subtle and only varies in the way parameters are passed. apply requires the second parameter to be array which represents the parameters to the function , and call accepts an argument list...

Let's quickly look at the syntax of both the functions., arg1, arg2, ....);

fun.apply(object, [argsArray]);

Hope you have enjoyed this post.

In subsequent post we will look at how to avoid this edge cases by using various well known pattern and practices.

JavaScript Scope

In this blog post we will dig deeper into various aspects of JavaScript scope.  This is a pretty interesting topic  and also a topic which confuses many beginning JavaScript programmers.

Understanding JavaScript scope helps you write bug free programs (hmm.. atleast helps your troubleshoot things easily)

Scope control the visibility and lifetimes of variables and parameters.  This is important from the perspective of avoiding naming collisions and provides memory management service.

Unlike other languages, JavaScript does not have block level scope.  For e.g. take for instance the following piece of c# code.
public void Main () {
int a = 5;
if (true) {
int b = 10;
// This will throw compile time error as b is not defined
// and not within the scope of function Main();

If you write the same code in JavaScript, then the value of 'b' will be available outside the 'if' block. The reason for this is JavaScript does not have block level scope. Scopes works at the function level and because of a feature called 'hoisting' all variable declaration in JavaScript is moved to the top of the function.

You can read more about hoisting here
function scopeDemo() {
var a = 5;
if (true) {
var b = 10;
// This will work even though 'b' is defined inside if block because of 'hoisting'

scopeDemo(); // Invoke the function

Remember, Scope in JavaScript is at function level and not block level.

So, contrary to popular guidelines of most programming lanaguage to declare variables as late as possible, in JavaScript it is recommended to declare all your variables as early as possible.

Happy Scoping !!!

You can try out the demo here

Thursday, March 22, 2012


Hoisting is one of the feature in JavaScript that puzzles many beginners and intermediate developers.  Hoisting is a feature wherein all the variables are moved to the outermost scope, which is function, in JavaScript.  This may sometimes result in seemingly strange behavior.

Before and after hoisting

The output of the above program is an alert with a value of 10.  Traditional logic would have lead us to believe that the value of alert should be undefined.  But because of hoisting the variable is moved to the top of function declaration.  Its important to realize that only the variable declaration is moved and not the initialization.
Recommendation: Always declare your variables at the top of the function scope.

Similar to variable hoisting we also have function hoisting.  Function hoisting has different behaviors based on the fact if the function is an expression or a declaration.

A function is an expression if it is assigned to a variable.  The assignment may also hold an anonymous or named function.   A function declaration is fully hoisted whereas a function expression has the hoisting behaviour of the variables as seen above.

Checkout the jsfiddle demo for a running application.

Watch out for next post where we will be demystifying "scope" in JavaScript.

JavaScript for Web and Library Developers

This is my first blog post on my home domain and in this series of posts I will explore various facets of JavaScript language that will help us become better programmers.  The idea is tear apart the language and understand how to use the features and build libraries like jquery, knockoutjs, backbonejs.

The idea is not to replicate this libraries, but understand the inner workings using better JavaScript coding practices, design principles and thereby make the web a better place to visit..

We will be covering the following topics, though not in order and there may be addition to this list.

  • Foundations

  • Patterns

  • Closure

  • this keyword

  • Hoisting

  • Anonymous function

  • Currying

  • Server side JavaScript

  • Canvas

  • etc.

Hope you will enjoy this journey with me!