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

88
Visualizações
update global variable with click event in js

I am beginner with JS.

I want to update global variable with click event, But I don't know how;

for example:

let a = 0;

example.addEventListener('click', () => {
a = 1;
console.log(a);
})

this prints

a = 1:

But i don't want to update it only in function, i want to update globally like below:

let a = 0;

example.addEventListener('click',() => {
a = 1;
})

console.log(a)

This still logs

a = 0

even it's clicked , But why? How can I update it globally with click event?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

when you run your code console.log(a) will not wait for the click event and hence it will log the current value of a which is 0, and it will not run again after firing the click event. You did not update it only in function but you just don't have anything to show you the updated value, instead you can do something like this:

let a = 0;
example.addEventListener('click',() => {
a = 1;
checkValue();
})

function checkValue() {
  console.log(a)
}
about 4 years ago · Santiago Gelvez Relatório

0

By default in js there is hoisting in which where ever the global variable is declare it will go to the top of the file in js.

let a = 0;
example.addEventListener('click',() => {
a = 1;
checkValue();
})

function checkValue() {
  console.log(a)
}

about 4 years ago · Santiago Gelvez 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