Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!