How to display updated localStorage data after page is refreshed?

Viewed 66

2 things I would like to accomplish here:

  1. I'm trying to display the new high score after the page is refreshed.
  2. The high score resets to 0 after refreshing due to localStorage.setItem('high_score', 0); so I'm not sure how to properly set this without resetting it to 0 every time the page is refreshed.
        let score = 0;
        var high_score = 0;
        localStorage.setItem('high_score', 0);

        document.getElementById('high_score').innerHTML="HIGH<br>SCORE:<br>" + 
        localStorage['high_score'];

        if (score > parseInt(localStorage.getItem('high_score'), 10)) {
            localStorage.setItem('high_score', score);
        }
1 Answers

You could only set the storage item except when you need to update it:

// assuming the scores will not be negative
const newHighScore = Math.max(localStorage.high_score, score);
localStorage.high_score = newHighScore;

And then when using the storage value, alternate with 0:

document.getElementById('high_score').innerHTML="HIGH<br>SCORE:<br>" + 
        (localStorage.high_score || 0)
Related