Better writing JS - from general variables to object This might be a dumb question for you advanced developers.

Below is a script on my own website that I want to modify, in order to avoid declaring same variables in each function. I want to avoid declaring variables in the main script structure.

Below code works, still wanted to know if there is a more elegant way to do this. 

As Answered below, it's best to enclose everything in an object.

var var1 = document.getElementById("div1");
var var2 = document.getElementById("div2");

function foo1(){
div1.style.display = "none";
}

function foo2(){
div2.style.display = "block";
}
You can enclose your variables (and functions) in a closure to restrict your scope, although you then need someway to make those functions callable outside of that closure, e.g.:

(function() {
    var a;

    function increment() {
        a += 1;
    }

    function decrement() {
        a -= 1;
    }

    window.increment = increment;
    window.decrement = decrement;
})();


It's pretty ugly, though.  It would be better to enclose the whole thing as an object, e.g.:

function Counter() {
    var count = 0;

    return {
        increment: function() {
            return count++;
        },
        decrement: function() {
            return count--;
        },
        value: function() {
            return count;
        }
    };
};