Number Guesser

Im bit stuck at Number guesser project on Full-stack dev course.
I should compare guesses between target number, but im bit off how to express it in If statement.


Create a compareGuesses() function. This function will be called each round to determine which guess is closest to the target number.

This function:

  • Has three parameters representing the user (human) guess, a computer guess, and the secret target number to be guessed.
  • Determines which player (human or computer) wins based on which guess is closest to the target. If both players are tied, the human user should win.
  • Return true if the human player wins, and false if the computer player wins.

Hi @mramcii
welcome to the forum!
So you have three values you have to compare. Create a simple line of math that subtracts the target value from each choice – the computer’s choice and the user’s choice – and store each of the calculations to a new variable. Then you can compare these two newly calculated values with each other in the if condition.

1 Like

Thanks this helped me alot, i was looking math.abs and didnt even think about new variables :slight_smile:

1 Like

This is what i came up with.

function compareGuesses(user, computer, secret) {

let userValue = Math.abs(secret - user);
let computerValue = Math.abs(secret - computer);

if (userValue > computerValue) {
    return true;
} else if (userValue < computerValue) {
    return false;
} else {
    return true;
}

}

Yes, that’s what I meant, but right now the wrong one wins. You want to let the one win which is closer to the secret. Right now you let the one with the bigger gap to the secret win.

Finished project, thank @mirja_t for great help! https://gist.github.com/ac89c2b365ed3ab938a73ac5cf2cdd25

1 Like