Search code examples
javascriptvariablesscopestate

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?


Solution

  • 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)
    }