Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda