-1

I'm trying to get my head around something re Scope/Closures.

I've setup an index.html with an app.js pulled in via <script>

The functions are accessible in things like <button onclick="increment();>"...

index.html

<body>
    <script src="app.js" type="text/javascript"></script>
    <button onclick="increment();"></button>
     <h2 id="number"></h2>
</body>

app.js

let total = 0;

function increment() {
    total += 1;
    document.getElementById('number').innerHTML = total;
}

setTimeout(() => {
  console.log('total is: ', total);
}, 5000)

So Scenario A above has a function that when called in html, increments the let total... fine. Then it posts it in the h2 tag/html. This works fine. And the timeout is there to test that 5 seconds later, it is indeed the let total... variable that's been incremented (i wondered before if i was creating a global variable within the function).

Scenario B calls a function (startGame() which itself calls the increment function with total passed in) but this doesn't work. Why would it lose scope of total?

app.js

    let total = 0;

function startGame() {
    console.log('game has started');
    increment(total);
    console.log('game has finished');
}
function increment(tot) {
    tot += 1;
    document.getElementById('number').innerHTML = tot;
}

setTimeout(() => {
  console.log('total is: ', total);
}, 5000)
Aid19801
  • 1,175
  • 1
  • 17
  • 30

1 Answers1

0

Scenario B calls a function startGame() which itself calls the increment function with total passed in, but this doesn't work.

That has nothing to do with it.

Why would it lose scope of total?

Because you've changed your increment function. You are no longer incrementing the global total variable, you are incrementing your local tot variable that was declared as a parameter.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375