const - JS | lectureDOM & Events Fundamentals

Implementing High Scores

DOM & Events Fundamentals

Let's now implement the last missing feature of our application: high scores. The high scores work the following way:

  • On page load, you have a score of 20 and a high score of 0
  • Then on your first game, let's say you win with a score of 10, then your high score will be ten because it's your first game.
  • On your next game, let's say you win with a score of 17, then your new high score will be 17 because 17 is greater than ten which was your previous high score.

Let's start by declaring the variable highScore and initializing it at zero

let highScore = 0;

Now, in the check button event handler, when checking if the user guess is equal to the secret number, add the below code because it's only when the user's guess is equal to the secret number that we set a new high score.

if (score > highScore) {
  highScore = score;
  document.querySelector('.highscore').textContent = highScore;

Now, if you reload and play it for the first time, you will notice that your high score is zero. Then if you win, your high score will be equal to your current score. Then, if your score is greater than your current high score, the latter will be updated the second time you play.