setting a variable in local storage

Lewis Waldron picture Lewis Waldron · Apr 26, 2013 · Viewed 37.6k times · Source

Currently designing a game and the idea is that of a high score, so that when the current score is more than the local storage one it is replaced:

localStorage.setItem('highScore', highScore);
var HighScore = localStorage.getItem('highScore');
if (HighScore == null || HighScore == "null") {
  HighScore = 0;
}

if (user.points > HighScore) {
  highScore = parseInt(HighScore);
}
return highScore 

Thanks guys

Answer

Anthony Ledesma picture Anthony Ledesma · Apr 26, 2013

This should point you in the correct direction.

// Get Item from LocalStorage or highScore === 0
var highScore = localStorage.getItem('highScore') || 0;

// If the user has more points than the currently stored high score then
if (user.points > highScore) {
  // Set the high score to the users' current points
  highScore = parseInt(user.points);
  // Store the high score
  localStorage.setItem('highScore', highScore);
}

// Return the high score
return highScore;