Javascript's variables grouping with object acting like namespace<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Javascript's variables grouping with object acting like namespace

Posted on: November 17, 2011

In Javascript, if you need to have multiple global variable in a script you could finish with something like a chunk of var.

1var v1;
2var v2;
3var v3;
4var v4;
5var v5;

This can cause problem because, maybe someone will need to define a variable with the same name (locally or globally). To reduce this problematic, you can use Javascript object notation (JSON). By using JSON syntax you can create a "virtual" namespace with an object. I say "virtual namespace" because it's not a namespace. In fact, it's an object... but it's created just to group variable instead if letting them wild at the top of a Javascript file. This is pretty important because if a web page include many Javascript file this could end having 2 files using the same variable name which would override the value of the other.

1var mynamespace = {
2 "v1":"value1" ,
3 "v2":"value2" ,
4 "v3":"value3" ,
5 "v4":"value4" ,
6 "v5":"value5" ,
7 "v6":"value6"
8};

This way, instead of using in your code v1 directly you use the object v1.

1mynamespace.v1 = "Patrick";
2
3//...
4
5if(mynamespace.v1 == "Unknown") {
6 //...
7}

This post cover only the basic. You can have multiple level of deepest as JSON let you have inner array or "object". I'll cover this later.