0

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

  • 1
    It is adding 1 each time you click! – Vishnudev Krishnadas Jul 10 '22 at 06:57
  • One solution would be to update the UI in your function when the score increments. – Yogi Jul 10 '22 at 07:04
  • This is not possible. Everything outside of the function executes *before* the user clicks. So just put the code that needs the updated value *inside* the function. – Bergi Jul 10 '22 at 07:18
  • We live in a universe that operates with linear time. You can’t use the result of clicking on the button 5 times **before** the button has been clicked on at all. – Quentin Jul 10 '22 at 08:19

1 Answers1

1

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>
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55