Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda