Home > Back-end >  Update global variables in two functions JavaScript
Update global variables in two functions JavaScript

Time:04-17

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();

})()

CodePudding user response:

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

  • Related