Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

})()
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!