Adding a high score to local storage
Solution 1
Try this:
var score = 0;
var highscore = localStorage.getItem("highscore");
if(highscore !== null){
if (score > highscore) {
localStorage.setItem("highscore", score);
}
}
else{
localStorage.setItem("highscore", score);
}
Solution 2
In addition to the parseInt
, you need to set the init value on the localStorage
first because localStorage.getItem("highscore",10)
doesn't returns 10 as default value if is not setted
var score = 0;
var highscore = 0;
localStorage.setItem("highscore",0);
Because when you check
if (score > parseInt(localStorage.getItem("highscore"))) {
localStorage.setItem("highscore", score);
}
The localStorage.getItem("highscore")
will return null if the item is not setted yet. Or you can also do:
var storagedHighScore = localStorage.getItem("highscore");
if (storagedHighScore || score > parseInt(storagedHighScore)) {
localStorage.setItem("highscore", score);
}
Solution 3
You need to retrieve the value from localStorage with
highscore = +localStorage.getItem("highscore")
or some equivalent code. Items in localStorage
don't track the global variables with the same names.
superman123
Updated on August 21, 2022Comments
-
superman123 over 1 year
I want to add a high score to my game. Right now I have this:
var score = 0; var highscore = 0;
The score variable works but whenever I get like points so total of 60 points it says the high score is still zero when checking it using
console.log(highscore)
.I have this to store the high score:
if (score > localStorage.getItem("highscore")) { localStorage.setItem("highscore", score); }
This does not work properly, but it also doesn't give any errors.