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
setItem()
call outside the function it is simply re-writing the exact same value that is already in there, bypassing the logic inwinLose()
, then no change would be visible. What behaviour are to expecting to see? You always need to write the score to localStorage within thewinLose()
function, as that's where the score is updated.score
.