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

109
Views
function behaves differently when using global variable
let outsideVariable = 5;

  function myFunctionTests(){
    let checkBox = document.getElementById("checkTests");
    let variableName = 10;
    if (checkBox.checked == true){
        variableName += 1;
        outsideVariable += 1;
        console.log('variableName is: ',variableName);
        console.log('outsideVariable is: ',outsideVariable);
    } else {
        variableName -= 1;
        outsideVariable -= 1;
        console.log('variableName is: ',variableName);
        console.log('outsideVariable is: ',outsideVariable);
    }
  }

When I run this code and I tick the checkbox, both variables ("variableName" and "outsideVariable") go up by 1 (output is 11 and 6). So far so good.

Now when I untick the checkbox, "variableName" goes down by 1 (based on the initial value of 10, so it goes to 9 as expected), but "outsideVariable" goes back to 5, instead of going to 4.

The only way to make "outsideVariable" go to 4 is to change

outsideVariable -= 1;

to

outsideVariable -= 2;

Any special reason why this happens? I'm learning JavaScript, so take that into consideration.

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

0

you want when checkbox uncheck, variableName = 10 and outsideVariable = 5, but they are equals to 9 and 4, right? for that problem you shoud define variableName in out of scope like global scope!.

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!