Phoenix
Phoenix

Reputation: 11

Javascript While Loop with Prompt Gathered variables

Hope you're all doing well ! I'm newbie with js and I've written the code below but it doesn't work the way I expected it to do. Need help ! The thing is, I want the loop to continue until "numberToGuess = guessNumber" but unfortunately, it breaks at second loop; even if numberToGuess is not equal to guessNumber. Can Someone explain me how to fix that please ? Thx!

const numberToGuess = Math.round(10*Math.random());
let guessNumber;

while(numberToGuess !== guessNumber){
guessNumber = prompt("Guess the hidden number: ");
if(guessNumber < numberToGuess){
console.log("Too low");
}else if(guessNumber > numberToGuess){
console.log("Too high");
}
}

console.log("Congrats ! You found it !");
console.log("Number to guess = " + numberToGuess + "\nGuessed number = " + guessNumber);

Upvotes: 1

Views: 90

Answers (2)

Prajakta Tamse
Prajakta Tamse

Reputation: 11

As correctly said by Ivar, prompt() always return value as string. If you want to compare it you can do as follows:

const numberToGuess = Math.round(10*Math.random());
let guessNumber;

    while(numberToGuess !== Number(guessNumber)){
    guessNumber = prompt("Guess the hidden number: ");
    if(guessNumber < numberToGuess){
    console.log("Too low");
    }else if(guessNumber > numberToGuess){
    console.log("Too high");
    }
    }
    
    console.log("Congrats ! You found it !");
    console.log("Number to guess = " + numberToGuess + "\nGuessed number = " + guessNumber);

Adding Number function will convert the string format into number format, so the comparison will be of numbers itself.

Upvotes: 1

EdwardKirk
EdwardKirk

Reputation: 455

You have to change the way you compare numberToGuess and guessNumber, by replacing !== with !=

Here's the code tested and working

const numberToGuess = Math.round(10*Math.random());
let guessNumber;

while(numberToGuess != guessNumber){
guessNumber = prompt("Guess the hidden number: ");
if(guessNumber < numberToGuess){
console.log("Too low");
}else if(guessNumber > numberToGuess){
console.log("Too high");
}
}

console.log("Congrats ! You found it !");
console.log("Number to guess = " + numberToGuess + "\nGuessed number = " + guessNumber);

Upvotes: 1

Related Questions