Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Global Objects

Tags:

javascript

Often I see a global object defined in javascript code to act as a namespace.

var MyNS = {a: function() {}, ... };

But sometimes, I see people leave off the "var" keyword like

MyNS = {a: function() {}, ...};

I believe in web browsers if you do not define a variable with var, it is put in the window object, which acts as a global namespace. Since it saves a few bytes of text by not using "var" is there a reason to use the keyword for this specific purpose ?

like image 752
Boris Yeltz Avatar asked Aug 16 '10 18:08

Boris Yeltz


2 Answers

Since it saves a few bytes of text by not using "var" is there a reason to use the keyword for this specific purpose ?

I wouldn't recommend you to avoid the var keyword, even if you are on Global Code.

The two ways seem similar but actually they are not the same, the first is a Variable Declaration, the Variable Object on global code, is the Global object itself, that's why global variables are accessible as properties of the global object (window.MyNS).

The second one is an undeclared assignment, it creates a property on the global object if the identifier is not found in the scope chain.

A real reason to avoid it is that in the new standard of the language, ECMAScript 5th Edition, under Strict Mode, an assignment to an undeclared identifier will throw a ReferenceError breaking your code.

There is also another subtle difference between your two examples, the Variable Instantiation creates the property on the global object that is non-deleteable:

var myVar = '';
delete window.myVar; // false
typeof window.myVar; // 'string'

While the undeclared assignment not:

myProp = '';
delete window.myProp; // true
typeof window.myProp; // 'undefined'

Recommended article:

  • Variables vs. Properties in JavaScript
like image 192
Christian C. Salvadó Avatar answered Oct 27 '22 00:10

Christian C. Salvadó


The use of var defines a local variable in the current scope. If you're in the global scope, they are effectively equivalent. The use of var there is more for understandability and maintainability, as the intention is absolutely clear. It's less clear without initializing the var.

In any local scope, if MyNS is initialized somewhere up the scope chain, you'll be overwriting that local variable rather than defining a global variable.

like image 43
eyelidlessness Avatar answered Oct 27 '22 00:10

eyelidlessness