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

140
Views
Retrieve value from x++ outside of a function - JavaScript

I have a little problem!

I need to retrieve the value of score++ outside of its function.

For example, if the user clicks "button" 5 times I want the score result to be 5.

How to use this result in a new function?

I searched without finding a solution.

let score = 0;
let clickHere = document.getElementById("clickHere");

clickHere.addEventListener("click", () => {
score++;
// console.log(score)
// Add 1 when I click
});

console.log(score);
// Score = 0
#clickHere {
padding: 20px;
background-color: #000000;
color: #ffffff;
font-weight: bold;
text-transform: uppercase;
display: inline-block;
}
<div id="clickHere">Click here !</div>

:).

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The console log outside the callback is executed only once. For every click, the event listener callback is executed. You can do all changes related to the variable there.

let score = 0;
let clickHere = document.getElementById("clickHere");
let counterDiv = document.getElementById("counter");

clickHere.addEventListener("click", () => {
  score++;
  counterDiv.innerText = "Counter: " + score;
  // console.log(score)
  // Add 1 when I click
});

console.log(score); // --> Already executed due to asynchronous nature
// Score = 0
#clickHere {
  padding: 20px;
  background-color: #000000;
  color: #ffffff;
  font-weight: bold;
  text-transform: uppercase;
  display: inline-block;
}
<div id="clickHere">Click here !</div>
<h4 id="counter">Counter: 0</h4>

about 4 years ago · Juan Pablo Isaza 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!