Dot Net For All

Learning Javascript – Namespace and scoping

In my previous posts I have discussed about functions and this keyword in javascript. In this post I will discuss about the scoping and namespace in javascript. How namespace can prevent from the prevention of the pollution of the code which is created due to lack of proper scoping.

Scoping in javascript

Unlike C# where every set of curly braces creates a scope, this is not the case with the javascript as we can see from the below code.

The variable b is created in the if block at global scope and I am trying to access the variable outside the if block and it is very clear that I can access it. Functions are the only place which create the scope in javascript unlike C# where an if block can also create a scope. Generally speaking anything with curly braces in C# creates scope which is not true with javascript.

Polluting the Global Scope

In javascript there is no notion of overloaded functions as whatever function we define takes over the previously defined function and same is the case with the variables where we do not get error if the same variable is defined multiple number of times.

Anonymous self executing functions

 To protect the global scope by having same functions and variables we can create function scope outside our variable and functions as shown below
function (){
    var firstName = "Vikram";
    var lastName = "Chaudhary";

    function CompleteName() {
        return firstName + " " + lastName;
    }
}

Here we have created a scope for the firstName and lastname variables by creating a function. But creating a function containing the CompleteName function will prevent us from accessing the CompleteName function from outside.

So we have to add the anonymous self executing function as shown in the below code snippet. Here we are creating a function which executes immediately as global scope is loaded by adding a parentheses at the bottom.

 (function (){
    var firstName = "Vikram";
    var lastName = "Chaudhary";

    function CompleteName() {
        return firstName + " " + lastName;
    }
})()

alert(CompleteName); //still doesn't work

But if we try to call the CompleteName function we will not be able to get to it. It is still lying in the anonymous function and having no way to access it.

Here we can pass a global object, which is window object for most of the browsers and add the items we want in the global scope to the global object.

In the code below we can see that we are adding the CompleteName function to the window object. And we call the function from global scope.

(function (w) {
    var firstName = "Vikram";
    var lastName = "Chaudhary";

    w.completeName = function () {
        return firstName + " " + lastName;
    }
})(window);

alert(completeName()); //vikram chaudhary

But after creating the global scope to the function we are at the same stage as we were initially having the CompleteName function defined at global scope.

Creating and Using namespace in Javascript

To overcome the shortcoming of global scope and anonymous self executing function with global scope the concept of namespaces has been introduced in the javascript.

I have created a namespace named person in javascript in as shown in the below figure.

Though there are various ways in which we can create a namespace in javascript but this is the best one as this way we can check if there is already a namespace named person in the same script file or in the script file parsed before this script, if yes then assign it to the person object, if not then create a empty object declaration as person namespace.

Once we have the namespace we can simple add the variables and functions to the namespace as I have done in the above figure.

In the below code there is another example where I have created another namespace in the person namespace.

person.address = person.address || {};
person.address.getAddress = function () {
    "My Address";
};

I have added a function to the address namespace named getAddress.

(function (per) {
    var firstName = "Vikram";
    var lastName = "Chaudhary";

    per.completeName = function () {
        return firstName + " " + lastName;
    }
})(window.person = window.person || {});

Now I am using the concept of namespace and self executing function to resolve the problem of the global scope pollution. Here I have created a function to which I am passing a namespace, and in the parameter of the self executing function I am passing the person namespace. I have created the person namespace in the global namespace by adding window.person as window is generally the alias for the global namespace for the javascript when we are working with browsers.

Here we are saying that if the person object is already created in the global namespace pass that in or otherwise let the person be the empty object where we are going to add the stuff.

This was all I wanted to discuss about the scoping and namespace in the javascipt.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview