Why can’t i output outside a function, in this scenario where i’m creating a simple counter i’m confused as to why it’s working inside and not out?

Tags: , ,



Why can’t I output outside the function here, why does it need to be inside?

counter = 0;

function countJar() {
  counter += 1
  document.getElementById('demo').innerHTML = counter;
}
// why can't it be here?

Answer

Because if it were where you’ve shown in the question, the value would be 0. The code runs immediately on page load, it doesn’t wait for something to call countJar. Where it is now, it doesn’t run until countJar is called.

If you mean you can’t even see 0 when you try to put it there, that would be because the id="demo" element doesn’t exist yet. If that’s what you mean, this question’s answers apply.



Source: stackoverflow