Monday, June 24, 2013

JavaScript global variable declaration tidbits

To make a global variable in JavaScript, type:

var thisHereThing = {};

You could make it even simpler:

thisHereThing = {};

They are the same thing (pretty much).


Let's try a practical example, a namespace for your app:

var TC =  TC || {};

Of course you may simplify it to:

TC =  TC || {};

Ouch! No, it doesn't work. What is going on here?

What happens is this. The js runtime tries to evaluate the right hand side of the equals sign. It finds a non-existing variable, TC, and gives up. But then, why does it work in the first example that starts with var? It turns out var statements get interpreted before the normal program flow. When the evalution of the right hand side takes place, the TC variable already exists and has an Undefined value.

Even the following piece of code won't throw an exception, even though b is used before its declaration.

var a = b;
var b;

If you wanted to skip the var keyword there still is a way to do that:

TC = window.TC || {};

Global variables are properties of the window object. And properties get created when they are used. So that works as well.

Learning and using JavaScript feels like exploring uncharted territories a lot more than using Java or C# does. Sometimes I like exploring.
Post a Comment

Archive