6

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 ?

asked Aug 16, 2010 at 18:12

4 Answers 4

8

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:

answered Aug 16, 2010 at 18:21
Sign up to request clarification or add additional context in comments.

3 Comments

+1 - Not only that, it is just plain sloppy. If you want to save a few bytes just minify the code.
So can we also declare the global variable by window.MyNS={}; and have the exactly same implication as var MyNS={}; ?
@Piccolo, well, not exactly the same, window.MyNS = {}; will create a property on the global object, while var MyNS = {}; will declare a variable, and as the global object, is the Variable Object of the Global Execution Context, a global property will be also created as consequence, I would recommend you give a look to the article I link in the answer.
2

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.

answered Aug 16, 2010 at 18:15

Comments

0

I think it's nice to use the keyword because it gets you in the habit, and helps prevent nasty errors when you forget it inside function bodies. It's also nice in case some global code finds itself migrated into a function.

But no, it's not strictly necessary.

edit — @eyelidlessness has a really good point, though if you're typing code at the global level already it's not an issue.

A fairly bulletproof pattern I've seen is to initialize global namespaces with something like this:

(function(window, undefined) {
 var foo = { stuff: "in my namespace", ... };
 window.foo = foo;
})(this);

At the global level, this will be the window object (if you're in a browser; if not, then it's whatever the global object is in that context).

answered Aug 16, 2010 at 18:16

Comments

-1

Douglas Crockford on this exact question: http://www.yuiblog.com/blog/2008/04/16/global-domination-part-two/

He settles on using a comment with the initialization, but without var. His analysis of the trade-offs is worth reading even if you disagree.

answered Aug 16, 2010 at 18:26

2 Comments

I'm a fan of Mr. Crockford but IHMO this is one of his worst articles. The three ways he describes are not completely equivalent, and there are possible hazards of using an undeclared assignment (the third way) under ES5 strict mode, moreover, his JSLint tool encourages the "use strict" directive without checking almost none of the rules of strict more :(
I think it's relevant to add that (obviously) the article is from, 2008, so it's no wonder that quite a few things have changed since then. I am currently reading "Javascript: The Good Parts" (Crockford is the author, also from 2008) and there are several sections of the book I have encountered so far that have derailed me for a few hours while I got to the bottom of the confusion. The book is highly recommended EVERYWHERE for honing your Javascript skills, but it could have used a 2nd Edition like 2 years ago!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.