Should I use window.variable or var?

JavascriptGlobal Variables

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 )

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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.

Solution 6 - Javascript

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).

Solution 7 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncbmeeksView Question on Stackoverflow
Solution 1 - Javascriptuser113716View Answer on Stackoverflow
Solution 2 - JavascriptLiviu T.View Answer on Stackoverflow
Solution 3 - JavascriptaepheusView Answer on Stackoverflow
Solution 4 - JavascriptJeremy RomanView Answer on Stackoverflow
Solution 5 - JavascriptzzzzBovView Answer on Stackoverflow
Solution 6 - JavascriptMrchiefView Answer on Stackoverflow
Solution 7 - JavascriptJustin LongView Answer on Stackoverflow