1

People say the lesser the number of global variable in your code,the better is your code.I have always used global variables in abundance.And my code works fine with that. So My question what is it that people find wrong in it.I am sure there must be a strong valid point behind it.

*If not for Global variables,What else?*What are other options for me to declare variables that have their scope in my entire code.

This is more of a theory question than usual stackOverflow question that have practical discussion,But I feel this question have a special importance as many javascript begineers would like to know the logic behind it.

HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87
  • and [I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?](http://stackoverflow.com/q/2613310) – Pekka Jun 23 '13 at 09:05

3 Answers3

1

Global variables are not that bad, it depends on the context. They really get in your way when you try to get things to work in parallel, but in Javascript you rarely do that.

They can pose a problem when you want to make things moduler and future-proof. Usually when you write Javascript code, you're writing small pieces of code and not one big system. So this isn't an issue.

zmbq
  • 38,013
  • 14
  • 101
  • 171
1

Global variables work just fine as long as you are writing all the code yourself, and only for yourself.

In web pages there are very often more than one script used. If they use global variables, they can conflict with each other. The less they add to the global namespace, the smaller the risk is to conflict with other scripts.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • and does var a or just a make a difference?? – HIRA THAKUR Jun 23 '13 at 09:23
  • @MESSIAH: That depends on where you use it. If you use `var` inside a function, it creates a variable that is local to that function. If you use variables without specifically decalring them, they are always created in the global scope. – Guffa Jun 23 '13 at 09:29
0

Others have answered about why not, but as far as your question on other options, you can use a limited number of objects, whether one created with the new keyword, or a simple literal, e.g.,:

var justOneGlobal = {
    someVariable1: 15,
    anotherVariable2: function () {alert('hello!');}
};

...which lessons the likelihood of interference since the only way this would be likely to conflict would be if someone else named their variable justOneGlobal.

Some people use the formal namespacing approach, as used in Java, like the following:

var com;
if (!com) {
   com = {};
}
if (!com.mySite) {
   com.mySite = {};
}
if (!com.mySite.example) {
   com.mySite.example = {};
}
com.mySite.example.someVariable1 = 15;

...but this approach feels pretty awkward and alien to JavaScript.

One handy way is to use an anonymous function. This prevents ANY globals at all (unless you wish to export some out of the function):

(function () {

    // Put all your code in here, making sure to use "var" when defining variables
    var someVariable1 = 15;

}());

// Code outside here won't know about `someVariable1`, so conflict is minimized.

Just because one has no global JavaScript variables does not mean, however, that one is guaranteed to avoid conflicts with other drop-in code.

One example, is if someone overrides the prototype of built-in objects, e.g.,:

Object.prototype.repeat = function (num) {
    return new Array(num+1).join(this);
};

...and then you try to use a for-in loop, you will actually bump into their code:

var str = 'abc';
for (var i in str) {
    alert(i); // "repeat" now shows up here
}

You can protect yourself against this as follows:

var str = 'abc';
for (var i in str) {
    if (str.hasOwnProperty(i)) {
        alert(i); // "repeat" now shows up here
    }
}

Similarly, if you modify the HTML DOM in a certain way, e.g., to add attributes onto elements as a means of keeping track of an element's state, if another application seeks to read or write attributes with the same name, there could be problems. The data-* attributes are meant to be used for storing data, but they don't provide formal namespacing (unlike namespaced attributes were going to promise for XML/XHTML), so there is some risk of one web application using the same attributes.

And this applies not only to what would be visible in mark-up like elements or attributes, but also "invisible" events, e.g., if you attach events in the old style without using addEventListener (or even if you do but someone calls preventDefault() or stopPropagation()), you (or other person) could overwrite one another's events.

Brett Zamir
  • 14,034
  • 6
  • 54
  • 77