Thursday, July 9, 2015

One good way to declare Global Variables in JavaScript

In JavaScript, declaring one variable as global is very easy, some one can say that if you just write a=3; "a" will be global, and if you write var a=3; then a is local (It is not at all true..!).

Let me explain first scope in JavaScript, JavaScript is functional level scoping language (not block level as C family languages) and any variable declared inside a function is not available to outer function (parent function).

Any variable directly declared or initialized outside (not inside any function) will be global variable

        var myVar = 3; // global variable 
        function myFun(){
            var funVar = 33; // this variable is not global, scope of this variable is within "myFun" function
        }
    
Below image explain it better on console, window is the root object in a browser, so if we declare any variable outside then it comes directly under window object:

In above snapshot window.funVar is undefined because this variable is not available globally because it is inside function "myFun".

Main aim of this post is to find out best way to keep all the global variables if required in an application. One question will come in mind that, why we should avoid global variables in an application??

Normally in an application there are many JS files and if any 2 or more files have same variable name and those are global then application will be messed up and it will really hard to find the issue sometime. So we should always avoid using global variables.

Before ECMA Script 5 strict mode, there were no way to check that inside function we have declared global variable by mistake. But now using "use strict" we can find out such issues.

We can create a class to have all the global variables inside that, and using getter nd setter method we can easily get and set the variables.

// how to use Global variables in JS
    var GlobalVariables = function () {
        // keep all the variables in this GlobalVars object
        var GlobalVars = {
            var1: 123,
            var2: 456,
            var3: "values"
        }
        this.get = function (name) {
            return GlobalVars[name];
        };
        this.set = function (name, value) {
            GlobalVars[name] = value;
        };
    };

    // craeate an object to fetch all the varibales and you can set also using get and set methods
    var global = new GlobalVariables();
Usage of above global object is as shown in console below:

No comments:

Post a Comment