Javascript’s variables grouping with object acting like namespace

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

var v1;
var v2;
var v3;
var v4;
var 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.

var mynamespace = 

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

  mynamespace.v1 = "Patrick";


  if(mynamespace.v1 == "Unknown")

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.