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.
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!.