im trying to change the value of a text inside an if statement but it doesnt work i think i use wrong logic

Issue

So i have made this code that when i click the check button it changes the text of message every time , depending on the number input in guess variable .

Though my logic to declare the variables in the beggining and then use them seems okey to me, it doesnt work
Can someone explain why my logic is wrong?

// for example i declared 
let message = document.querySelector('.message').textContent;

//and then i used message inside if to change the text
message = '‼ Type a Number';

why is this wrong?

document.querySelector('.check').addEventListener('click', function () {
      let score = 20;
      const guess = Number(document.querySelector('.guess').value);
      let message = document.querySelector('.message').textContent;
      if (!guess) {
        message = '‼ Type a Number';
      } else if (secretNumber === guess) {
        message = 'You Won 🥳';
      } else if (secretNumber < guess) {
        message = 'It is a lower Number!';
        score += -1;
        document.querySelector('.score').textContent = score;
      } else if (secretNumber > guess) {
        message = 'It is a higher Number!';
        score += -1;
        document.querySelector('.score').textContent = score;
      }
    });

Solution

Your problems (or the two that jump out at me) are that you redefine score every time the function is run. That is, every time you click the button, score is reset to 20 and can only take on values of 20 or 19 depending on the user’s input. The other problem is you never re-assign the textContent of the .message element.

To resolve this, just move that declaration of score outside of the function and add an extra message reassignment line like so:

let score = 20;
document.queyrSelector(".check").addEventListener("click", function() {
    // the 'let score' line has been removed from in here
    const guess = Number(document.querySelector('.guess').value);
    let message = document.querySelector('.message').textContent;
    // Rest of your code ...
    document.querySelector(".message").textContent = message;
});

Also note (as Bravo pointed out) that your use of += and - overlaps – you should just use the compound assignment operator with subtraction (i.e., score -= 1 not score += -1. This also works for other operators, such as multiplication *= and division /=.)

Answered By – Jack Bashford

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.