Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update global variables in two functions JavaScript

Though I am aware of "Global scope, function scope, block scope" in JavaScript. I got stuck in this code block.

I simplified the logics of the code as follows. What I expected is, the console.log(a, b, c) in execute function would be a = 3, b = 6, c = 9.
But what I actually got is a = 0, b = 0, c = 0. What’s going wrong and how to fix this? Thanks

(function() {
    let a,b,c;
    let conditions = [-1, 1, 2, 3 ];

    const execute = () => {
        for (let i=0; i<conditions.length; i++) {
            if (conditions[i] < 0) {
                a = 0;
                b = 0;
                c = 0;
            } else if (conditions[i] > 0) {
                update(a, b, c);
            }
        }
        console.log(a,b,c);
    }

    const update = (a, b, c) => {
        a = a + 1;
        b = b + 2;
        c = c + 3;
    }

    execute();

})()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here, by not declaring params to update(), the assignments are made to the variables in the parent scope.

(function() {
    let a,b,c;
    let conditions = [-1, 1, 2, 3 ];

    const execute = () => {
        for (let i=0; i<conditions.length; i++) {
            if (conditions[i] < 0) {
                a = 0;
                b = 0;
                c = 0;
            } else if (conditions[i] > 0) {
                update(); // edit
            }
        }
        console.log(a,b,c);
    }

    const update = () => {
        a = a + 1;
        b = b + 2;
        c = c + 3;
    }
    execute();
})()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading