Why and How to avoid Global variables in javascript – By Arindam

Hey Developers and Geeks,

This post will mostly be on the Javascript Global and local variables.

Before I start, these are some basic inputs which I would like to input:

Local variable: A variable whose scope is limited to the function it belongs.

Ex:

function f_local(){

var a=5; // local to this function

}

Global variable: The variables which is declared outside a function scope and can be accessed from anywhere in the script.

var a=5;

function f_global(){

console.log(a); // Its able to access a

}

Two variables of same name:

var a=5;

function f_local(){

var a=10;

console.log(a);  // this will output 10

}

Now How and Why to Avoid using Global variables:

First it comes to out mind why we should avoid using Global variables.

Its not that Global variables are bad or harmful in a way. Though easily a user can access your variables from Console. No matter what you can access the data within variables which are in js. We can make it tough by embedding in other vars, functions or wrappers but its not impossible to fetch the values.

So security is not a concern here. What concerns is that it should not re-write or overwrite values of another variables. If we use global variables and a lot many of them, in future maintenance becomes a big concern. We may accidentally use a same variable name and hence introduce a major bug to the system.

Approach:

Best Approach to avoid accidental over-ride is to wrap the variables in a json style var.

Example:

var Wrapper1={

   a:5,

   b:function(obj){

}

};

So we can call like this: Wrapper1.a or Wrapper1.b(someobj);

Another interesting way is to use Singleton wrapper and hide the vars to have direct access. instead we can have setters-getters for them.

var appWrapper = (function() {

var tilename=””;

return {
getTilename: function() {
return tilename;
},
setTileName:function(tile){
tilename=tile;
}

};
})();

We can then access using: appWrapper.getTilename();

Note: appWrapper.tilename is NOT going to work.

Thanks,

Arindam

twitter: arindamlahiriit
Gtalk: lahiri.ari@gmail.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s