Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope and sharing information without global variables

If I have:

function firstFunction(){
    var counter = 0;
    secondFunction();
    secondFunction();
    secondFunction();
    secondFunction();
}
function secondFunction(){
    counter++;
}

I get an error because of the local scope of the variable, but how else am I to do something like this without using global variables?

like image 384
dezman Avatar asked Mar 13 '26 00:03

dezman


2 Answers

One way is to use a closure:

(function() {
    var counter = 0;

    function firstFunction() {
        secondFunction();
        secondFunction();
        secondFunction();
        secondFunction();
    }

    function secondFunction() {
        counter++;
    }
})();

Alternately, you could pass in the value of counter to secondFunction, like this:

function firstFunction() {
    var counter = 0;
    counter = secondFunction(counter);
    counter = secondFunction(counter);
    counter = secondFunction(counter);
    counter = secondFunction(counter);
}

function secondFunction(counter) {
    return ++counter;
}
like image 128
Elliot Bonneville Avatar answered Mar 14 '26 15:03

Elliot Bonneville


Use Object to pass counter by reference

   function firstFunction() {

        var myObj = new Object();
        myObj.counter = 0;

        secondFunction(myObj);
        secondFunction(myObj);
        secondFunction(myObj);
        secondFunction(myObj);

    }

    function secondFunction(obj) {
        obj.counter++;
    }
like image 34
Yuriy Galanter Avatar answered Mar 14 '26 15:03

Yuriy Galanter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!