56

We have a lot of setup JS code that defines panels, buttons, etc that will be used in many other JS files.

Typically, we do something like:

grid.js

var myGrid = .....

combos.js

var myCombo = .....

Then, in our application code, we:

application.js

function blah() {
    myGrid.someMethod()
}

someother.js

function foo() {
    myCombo.someMethod();
    myGrid.someMethod();
}

So, should we be using the var myGrid or is better to use window.myGrid

What's the difference?

0

7 Answers 7

65

A potentially important difference in functionality is that window.myGrid can be deleted, and var myGrid can not.

var test1 = 'value';
window.test2 = 'value';


console.log( delete window.test1 ); // false ( was not deleted )
console.log( delete window.test2 ); // true  ( was deleted )


console.log( test1 );  // 'value'         ( still accessible )
console.log( test2 );  // ReferenceError  ( no longer exists )
3
  • 12
    This is the best answer, on the basis that it actually answers the question. Commented Jun 26, 2014 at 9:27
  • "var" appears to call Object.defineProperty with configurable=false Commented Oct 22, 2014 at 0:33
  • 1
    in the property descriptor, configurable:false is the only difference. See (jsbin.com/zazuzi/edit?js,console) Now, why is there this difference? It seems to be answered here (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…), where it says delete is only effective on an object's properties. It has no effect on variable or function names. The fact that a global variable does reside on the global object is an "implementation" detail, but the intent and characterization of a declared variable is preserved via the configurable flag.
    – Joe Hanink
    Commented Feb 24, 2016 at 18:08
43

I would suggest creating a namespace variable var App = {};

App.myGrid = ...

That way you can limit the pollution of the global namespace.

EDIT: Regarding the number of variables issue - 2 possible solutions come to mind:

  1. You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc)
  2. You encapsulate your methods in objects that get instantiated with the components you have

ex: you have

function foo() {
    myCombo.someMethod();
    myGrid.someMethod();
}

becomes:

var Foo = function(combo, grid) {
    var myCombo = combo;//will be a private property
    this.myGrid = grid;//will be a public property
    this.foo = function() {//public method
        myCombo.someMethod();
        myGrid.someMethod();
    }
}
App.myFoo = new Foo(someCombo, someGrid);
App.myFoo.foo();

this way you limit the amount of little objects and only expose what you need (namely the foo function)

PS: if you need to expose the internal components then add them to this inside the constructor function

6
  • 1
    +1 This is what my answer would have been. This also has the benefit of creating a unique name that will identify your app from somebody else's.
    – qw3n
    Commented Aug 1, 2011 at 20:57
  • 1
    I like this idea. However, is it still practical if we have literally hundreds or maybe even thousands of little objects like buttons, number fields, etc all inside the App global?
    – cbmeeks
    Commented Aug 2, 2011 at 12:30
  • 1
    @cbmeeks well no one stops you from further namepacing you variables App.Grids.myGrid etc
    – Liviu T.
    Commented Aug 2, 2011 at 12:54
  • 1
    So... just to be clear (four years later), your answer is var. All this business about namespacing is really orthogonal to the question. The namespace itself is still a global variable and has to be created with one method or the other.
    – harpo
    Commented Oct 27, 2014 at 4:38
  • 1
    @cbmeeks - if you have thousands of (named) objects, then it is even more valuable to declare those as part of some master object such as App. If you don't, then you are adding those thousands of names to "window" - that won't be any more practical - they always are attached to something. Commented Oct 15, 2019 at 11:30
11

One nice use of window.variable is that you can check it without having a javascript error. For example, if you have:

if (myVar) {
    //do work
}

and myVar is not defined anywhere on the page, you will get a javascript error. However:

if (window.myVar) {
    //do work
}

gives no error, and works as one would expect.

var myVar = 'test' and window.myVar = 'test' are roughly equivalent.

Aside from that, as other said, you should descend from one global object to avoid polluting the global namespace.

1
  • Its worth mentioned that using MyApp.myVar (see the accepted answer) has the same benefit as window.myVar (as long as MyApp has been declared somewhere). var App = {}; ... App.myVar = "whatever"; ... if (App.myVar) ... ... if (App.thisVarWasNeverDeclared) {...} - no error, just skips that code. To test if never declared: if (App.myVar === undefined) { App.myVar = "some default"; }. Commented Oct 15, 2019 at 11:36
8

In global scope the two are in fact equivalent functionality-wise. In function scope, var is certainly preferable when the behaviour of closures is desired.

I would just use var all of the time: firstly, it's consistent with the usually preferred behaviour in closures (so it's easier to move your code into a closure if you decide to do so later), and secondly, it just feels more semantic to me to say that I'm creating a variable than attaching a property of the window. But it's mostly style at this point.

4
  • 7
    They are not quite equivalent. Properties of window can be deleted using the delete operator whereas variables declared using var cannot be deleted. Also, code only using var is portable to non-browser environments.
    – Tim Down
    Commented Aug 1, 2011 at 23:35
  • Tim: Even in global scope? This works for me (in Chrome, at least): var x = 10; delete window.x;. The latter statement returns true, and when I try to reference x thereafter I get a ReferenceError. I haven't read the specification, though, so it's possible V8 is non-compliant in this way. Commented Aug 1, 2011 at 23:37
  • So I was. I stand corrected; I should be more careful about verifying edge cases like this in the JavaScript console Commented Aug 1, 2011 at 23:51
  • 1
    @Tim Down +1 for reminding me that not all JS will run client side.
    – cbmeeks
    Commented Aug 2, 2011 at 12:14
6

The general answer to the question would be to use var.

More specifically, always put your code in an Immediately Invoked Function Expression (IIFE):

(function(){
  var foo,
      bar;
  ...code...
})();

This keeps variables like foo and bar from polluting the global namespace. Then, when you explicitly want a variable to be on the global object (typically window) you can write:

window.foo = foo;

JavaScript has functional scope, and it's really good to take full advantage of it. You wouldn't want your app to break just because some other programmer did something silly like overwrote your timer handle.

3

In addition to other answers, worth noting is that if you don't use var inside a function while declaring a variable, it leaks into global scope automatically making it a property of window object (or global scope).

3

To expand on what Liviu said, use:

App = (function() {
    var exports = {};
    /* code goes here, attach to exports to create Public API */
    return exports; 
})();

By doing that you can hide some of your implementation specific code, which you may not want exposed by using var's inside. However, you can access anything attached to the exports object.

Not the answer you're looking for? Browse other questions tagged or ask your own question.