const - JS | lectureDOM & Events Fundamentals

Refactoring our Code

DOM & Events Fundamentals

To finish this project, let's now learn the refactoring technique to get rid of some of our duplicates. As you might have noticed up until now, we have some repeated code in our current codebase. Have a look at the below code.

script.js
else if (guess > secretNumber) {
  if (score > 1) {
    document.querySelector('.message').textContent = '📈 Too High!';
    score--;
    document.querySelector('.score').textContent = score;
  } else {
    document.querySelector('.message').textContent = '💥 You lost the game!';
    document.querySelector('.score').textContent = 0;
  }
} else if (guess < secretNumber) {
  if (score > 1) {
    document.querySelector('.message').textContent = '📉 Too Low!';
    score--;
    document.querySelector('.score').textContent = score;
  } else {
    document.querySelector('.message').textContent = '💥 You lost the game!';
    document.querySelector('.score').textContent = 0;
  }
}

You will notice that both of them are equal, and the only thing that changes is the string we display if the guess is too high or too low. If you remember, having a lot of duplicates violates the DRY (Don't Repeat Yourself) principle.

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

It's really bad to have duplicate code because when we want to change a piece of functionality, we have to change the same code in multiple places. For example, we might want to change the message when the player loses the game. i.e. 'You lost the game!'. For that, we will have to change it in both conditions. For a small app like the one we are building, it's not a big problem, but it can quickly become a nightmare for a bigger codebase. So try to avoid duplicate code whenever you can.

However, when we first write some code, it's not a big problem to start with duplicate code reason why I wrote mine the way I did. This is because I just wanted to make it work. But then, as we move on in the project, we can use a technique called refactoring. Refactoring means restructuring the code (improving or optimizing our codebase) but without changing how it works.

The first step is to identify duplicate code that I just showed you above to improve our code. To eliminate our duplicates, we can notice from the above code that the first else if condition checks if the guess is too high and the second if the guess is too low. But in both cases, what we are really doing is to check if the guess is different from the secret number.

So whenever the guess is different from the secret number, then the code inside is executed where the only thing that changes is the string we set to the element with the class message. So instead of having one big block of code when the guess is too high and another when it is too low, let's just have one block for the situation where the guess is different.

What we are going to do is add another else if block for the case where guess is different from secret number. Then, use a ternary operator to change the string when guess is too high or too low. Here is what I mean:

script.js
else if (guess !== secretNumber) {
  if (score > 1) {
    document.querySelector('.message').textContent =
      guess < secretNumber ? '📉 Too Low!' : 'Too High!';
    score--;
    document.querySelector('.score').textContent = score;
  } else {
    document.querySelector('.message').textContent = '💥 You lost the game!';
    document.querySelector('.score').textContent = 0;
  }
}

You can now safely delete the two previous else if blocks we had. Save all files and try it again. Everything should still work as expected.

We fixed the duplicate issue by simply condensing two versions of the same code into just one. However, sometimes, a good refactoring technique is also to create functions. For example, you will notice that the below code can be found in multiple places in our current codebase.

script.js
document.querySelector('.message').textContent

The same is true for number, score, secretNumber etc. Whenever that happens, we can also refactor the same code in a function and then call the function in all the places where we have to duplicate code.

I am just going to do it for the message, and you can do the rest on your own. Try taking it as a challenge! So what I'm going to do is create a function called displayMessage with a parameter called message.

script.js
const displayMessage = function (message) {
  document.querySelector('.message').textContent = message;
};

All we now have to do is call it wherever we set the text content of any element with the message class.

script.js
if (!guess) {
  displayMesssage('No number');
}

You can now go ahead and replace all the other occurrences.

To finish this lecture, always keep refactoring in mind when you write your code, and of course, we will do a lot of refactoring throughout the following lectures. Anyway, we finished the project with this, and I hope you liked it as I did. In the next lecture, we are going to build another project, so stay tuned!