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?

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
cbmeeks
  • 11,248
  • 22
  • 85
  • 136

7 Answers7

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 )
user113716
  • 318,772
  • 63
  • 451
  • 440
  • 12
    This is the best answer, on the basis that it actually answers the question. – Ben Griffiths Jun 26 '14 at 09:27
  • "var" appears to call Object.defineProperty with configurable=false – Sarsaparilla Oct 22 '14 at 00:33
  • 1
    in the property descriptor, `configurable:false` is the only difference. See (http://jsbin.com/zazuzi/edit?js,console) Now, why is there this difference? It seems to be answered here (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete), 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 Feb 24 '16 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

Bridge
  • 29,818
  • 9
  • 60
  • 82
Liviu T.
  • 23,584
  • 10
  • 62
  • 58
  • 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 Aug 01 '11 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 Aug 02 '11 at 12:30
  • 1
    @cbmeeks well no one stops you from further namepacing you variables App.Grids.myGrid etc – Liviu T. Aug 02 '11 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 Oct 27 '14 at 04:38
  • @harpo well the underlining problem was that he had lots of things that needed creating so a namespace is the solution instead of poluting the global namespace, but it is true that var vs window is not important. Only in a non browser environment is var the only solution. – Liviu T. Oct 27 '14 at 14:26
  • 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*. – ToolmakerSteve Oct 15 '19 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.

Roman
  • 4,922
  • 3
  • 22
  • 31
aepheus
  • 7,827
  • 7
  • 36
  • 51
  • 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"; }`. – ToolmakerSteve Oct 15 '19 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.

Jeremy Roman
  • 16,137
  • 1
  • 43
  • 44
  • 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 Aug 01 '11 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. – Jeremy Roman Aug 01 '11 at 23:37
  • So I was. I stand corrected; I should be more careful about verifying edge cases like this in the JavaScript console – Jeremy Roman Aug 01 '11 at 23:51
  • 1
    @Tim Down +1 for reminding me that not all JS will run client side. – cbmeeks Aug 02 '11 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.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
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).

Mrchief
  • 75,126
  • 20
  • 142
  • 189
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.

Anish Gupta
  • 2,218
  • 2
  • 23
  • 37