0

I have this code when when you click a button, it randomly generates a win or lose count; I want to save the score of the win/lose counts so even when the page is refreshed I can still continue.

My problem is that when I put the localStorage.setItem() within the function, it runs perfectly and updates the score every time, but when I put the localStorage.setItem() **outside of the function, then when the page is refreshed it starts all the way back as if the score wasn't updating.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>functions</title>
</head>

<body>
  <button onclick="
        winLose()
      ">Click to win</button>
  <script>
    const score = JSON.parse(localStorage.getItem('score'));

    function winLose() {
      const evaluatedNumber = Math.random();
      if (evaluatedNumber > 0 && evaluatedNumber <= 0.5) {
        score.lose++;
        console.log(`You lost, lose count: ${score.lose}`)
      } else if (evaluatedNumber > 0.5 && evaluatedNumber <= 1) {
        score.win++;
        console.log(`You won, win count: ${score.win}`)
      }
    }

    localStorage.setItem('score', JSON.stringify(score))
  </script>
</body>

</html>

I am pretty sure the answer might be something very simple but I can not connect the dots here. I am also beginner so a simpler language used for explaining will be much appreciated

2
  • 2
    Given that when you put the setItem() call outside the function it is simply re-writing the exact same value that is already in there, bypassing the logic in winLose(), then no change would be visible. What behaviour are to expecting to see? You always need to write the score to localStorage within the winLose() function, as that's where the score is updated. Commented Jul 10 at 9:27
  • 2
    The logic of your code is this, load from localestorage , save to localestorage, run rest of code never touching localestorage again. Localestorage won't automatically save for you when you update score.
    – Keith
    Commented Jul 10 at 10:44

1 Answer 1

0

First of all we should know that during page loading. JS engine read all the codes from top to bottom.

As pseudocode example :

ReadFromFile

function DoingSomething(){ ... }

WriteToFile

During page load JS Engine read and operate first line. Then for second line (for function) creates a structure in memory that allows functions to be called later. Not invoke this function. Then read third line and operate it. (means write to file but without DoingSomething function. This function will operate after call in your case after click button).

So every page load (refresh) ReadFromFile and WriteToFile codes will run.

console.warn("Reading from file.");

function something(){
  console.log("this is something function that will write..");
}

console.warn("Writing to file.");
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <p>During every refresh 'reading' and 'writing' logs appear but 'function something' NOT</p>
  <button onclick='console.log("log")' >Call func.</button>
</body>
</html>

Not the answer you're looking for? Browse other questions tagged or ask your own question.