Search code examples
javascriptjqueryglobal-variablesstore

What is the best way to store a value for use in a later function? I'm hearing global variables are evil


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?


Solution

  • 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);
    }