0

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

})()
2
  • 4
    Your update() function defines its own a, b, and c parameters, which hide the local variables in the external function scope. Commented Apr 16, 2022 at 23:30
  • 2
    To restate @Pointy, the assignments in update() change that function's parameters, which have no relationship to the variables in the containing scope. To get expected results, delete update's params. update = () => ... Commented Apr 16, 2022 at 23:32

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ah... I learned that both the arguments and parameters in update() are unnecessary. Thanks
@Judy - I should have mentioned that the arguments aren't necessary either. Please see edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.