1

I can't get the following code to say anything other than undefined. What am I not doing right? I'm not sure how the score function works, either. So far I've only written vanilla function doSomething() {} methods. Thank you.

var score = score || {};

score = {
  saveHighScore: function(tally) {
    var high_score = localStorage.high_score;
    if (typeof high_score == 'number') {
      if (tally > high_score) {
        localStorage.high_score = tally;
      }
    } else {
      localStorage.high_score = tally;
    }
  },
  getHighScore: function() {
    var high_score = localStorage.high_score;
    if(typeof high_score !== 'number') {
      high_score = 0;
      localStorage.high_score = high_score;
    }
    return high_score;
  }
}

window.console.log("Score: ", score.getHighScore());
listenlight
  • 654
  • 1
  • 12
  • 27

1 Answers1

1

your problem is local storage stores values as string key/value pairs, so you need to parseInt:-

var score = score || {};

score = {
  saveHighScore: function(tally) {
    var high_score = localStorage.high_score;
    if (typeof high_score == 'number') {
      if (tally > high_score) {
        localStorage.high_score = tally;
      }
    } else {
      localStorage.high_score = tally;
    }
  },
  getHighScore: function() {
    var high_score = parseInt(localStorage.high_score);
    if(typeof high_score !== 'number') {
      high_score = 0;
      localStorage.high_score = high_score;
    }
    return high_score;
  }
}

score.saveHighScore(100)

window.console.log("Score: ", score.getHighScore());

I have no idea why, but I reloaded the same code posted above and it returns Score: 0 in the console.

The reason it is returning 0, is inside getHighScore it retrieves the value from local storage and compares to see if its not a number, then if it isn't you are setting it to 0. as local storage saves all values as a string it is always setting your value to 0.

I'm not sure how the score function works, either

these are just functions inside an object.

BenG
  • 14,826
  • 5
  • 45
  • 60