So the code I'm using is at http://jsfiddle.net/8j947/10/ and it returns a value of true or false for the variable isLive. How can I use the variable onLive in a later function? I read the answers at Accessing variables from other functions without using global variables, but I'm having a lot of trouble getting it to work. All I want is to store the value, true or false, so I can call it into an if statement in a later function. Can anyone give me the simplest way to do this? Is there a way to store the data as an object?
-
Bind it to an element using the data function. http://docs.jquery.com/Data – Gazler Aug 11 '11 at 20:35
-
2Wow, someone is going downvote crazy on answers to this question. – kakridge Aug 11 '11 at 20:45
-
It's not me, but i kinda understand why. A bunch of the answers say something like "use a namespace". A global in a namespace is *still a global*. – cHao Aug 11 '11 at 21:03
-
Yes, I was considering that. That's still a contested gray area. Namespaces are considered a solution to some of the common problems with using global scope, but they still use global scope to solve. – kakridge Aug 11 '11 at 23:04
7 Answers
Just define your variable in the same scope as you are defining your functions that rely on it. If your functions are in the global scope, then so should your variable be.
If you are developing a plugin or control or a script that will be used in more than one page, then yes, avoid global variables. If, on the other hand, you have a page-specific piece of data that you need available in more than one location, a global variable is absolutely appropriate.
Sometimes you have to understand the rules, so that you know when it's ok to break them.
Now, if you just now realized that your functions are in the global scope, and you want to change that, just wrap all of your code in an anonymous function and call it immediately:
(function(){
var scopeLevelVariable = true;
function scopeLevelFn(){
...
}
window.globallyAvailableVariable = "foo";
window.globallyAvailableFunction = function(){
...
};
})();
Global variables are considered "evil", because any function could inadvertently modify your variable, which can cause some hard-to-track bugs. This usually isn't a problem for simple projects, but it's something you should think about.
To save a value without muddying the global namespace too much, and thus reduce the risk of the aforementioned bugs, you can create you own "namespace" object (Option 2 of the accepted answer in the question you linked). Like so:
var MyPageData = {};
MyPageData.someProperty = someFunc();
// Later on...
function anotherFunc() {
// Use the data you set...
alert(MyPageData.someProperty);
}

- 22,904
- 4
- 58
- 91
-
2A namespaced global isn't much better. The problem with globals isn't so much even accidental modification -- it's the much broader problem of "action at a distance". The more global something is, the less you can say about what code modifies it, whether intentionally or accidentally. Stuffing global variables into a namespace might protect you a tiny bit from other people's code, but it won't protect you from *your own*. – cHao Aug 11 '11 at 20:56
-
2@cHao You're right, but this isn't meant to be the end-all/be-all solution. For smaller projects, this is perfectly viable. The OP can make their own decision about whether this kind of solution is right for them. I guess I'm just less dogmatic about the "globals are evil" issue. – FishBasketGordo Aug 11 '11 at 21:01
-
I'm not really dogmatic about it, but it's so easy to keep a variable out of global scope (via closures, `this.variable`, etc) that i find i just don't need globals for much of anything. – cHao Aug 11 '11 at 21:07
-
-
allthough this is simple, and makes a valid point, I think it misses the best solution, which is well explained by @gilly and there is an example of in my answer. Also as cHao comments here, it is better to encapsulate your self contained code in some kind of anonymous function. It is my opinion that this method is the best approach to your problem, but sometimes you need to have a global variable to allow for certain interactions between modules, and when that is the case, it should be limited to a single namespaced object to avoid further polution. Happy coding. – Billy Moon Aug 12 '11 at 09:48
-
3Namespaced globals are used all the time.. how about in ALL major libraries? It's perfectly acceptable to make global some data. – John Strickler Aug 12 '11 at 12:44
I would not agree that global variables are evil in themselves, just that there are a few precautions to take whilst using them.
To avoid colision with other global variables (possibly ones written in included libraries) I would suggest taking two measures
1) Use anonymous functions (self envoking) to keep your code (and variables) seperated from other code
// other peoples/modules code
var myVariable = "whatever";
// anonymous function for your self contained code
(function(){
var myVariable = "inside closure";
alert(myVariable);
})() // the empty brackets envoke the anonymous function
// still retains value from before your self envoking anonymous function
alert(myVariable);
2) Use unique namespace - and make all globals you use under that one object to avoid polution
myUniqueNameSpaceRaiders = {};
// will not conflict with other global variables if your namespace is unique
myUniqueNameSpaceRaiders.desiredVariable = "something";
I think if you organise your global variables well, it is fine to use them. Hope this helps.

- 57,113
- 24
- 136
- 237
-
That is not actually a closure, it is a self invoking anonymous function. See this answer: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work/111200#111200. That's not to say there is anything wrong with your answer though! :-) – gilly3 Aug 11 '11 at 20:51
If you're working with some specific set of functions and data, you could do something like this:
var yahooInterface = new function(){
var isLive = false;
this.function1(){ isLive = true };
this.function2(){ alert( isLive ) };
};
In this manner, function1
and function2
share data, but they don't wastefully pollute the global namespace.
Example: http://jsfiddle.net/XpJFn/1/

- 66,414
- 68
- 253
- 406
Try modular javascript programming .
Also, closures are useful for holding information w/o exposing it to the global namespace.
If you must use a global... create your own global namespace and put anything you need inside of it. This may be a good starting point for you as you venture into other javascript patterns.
Ex.
//Global Namespace
window.ns = {};
ns.onLive = false;
if(ns.onLive === false) {
ns.notLive = !ns.onLive;
}
//Closures
var hello = (function() {
var onLive = true;
my.fn1 = function () {
return onLive;
}
my.fn2 = function () {
return !onLive;
}
return my;
})();
hello.fn1(); //true;
hello.fn2(); //false

- 25,151
- 4
- 52
- 68
-
1I'd say because your code leads with the example of namespacing a global, which (while semi helpful at times) doesn't resolve the issues around *having* a global in the first place. It does some weird thing with `ns.notLive` that should be avoided in real code. And your closure example is sorely lacking -- it provides no example of actually using (read: modifying) `onLive` once you've enclosed it. Oh, and it doesn't work -- there should probably be a `()` at the end of the closure definition, though i don't see why you do things that way. I didn't downvote (yet), but i'm considering it. – cHao Aug 11 '11 at 21:35
-
What's funny is the ACCEPTED answer uses a global namespace object. So it seems my answer was spot on for the OP. Care to rebuttal? – John Strickler Aug 12 '11 at 12:43
If you're deadset against using global variables, you could just create a method that returns the variable.
getVariable = function(){
return "Hello world!";
}
Global variables are not inherently evil though, when they're used properly. Just don't use them if you don't need to. If there's a good justification for using a global variable, there's nothing wrong with that.

- 45,496
- 8
- 73
- 110
-
This is still a global. The extra `function` around the value provides no protection, as i could replace it with `getVariable = function() { return "Go away"; };`. – cHao Aug 11 '11 at 21:27