Home > Net >  Why do I need an additional parseInt for this code to work property?
Why do I need an additional parseInt for this code to work property?

Time:08-17

From my understanding the code below converts the user input into an integer and writes it to the variable called guess:

let guess = parseInt(prompt("enter number here))

That being the case is there any point in including an additional parseInt in the following while loop? I ask because the code seems to break whenever I omit it.

while (parseInt(guess) !== targetNumber){
if (guess > targetNumber) {
    guess = prompt("Too high! Enter a new guess:");
} else {
    guess = prompt("Too low! Enter a new guess:");
}

CodePudding user response:

parseInt is a method that returns number but it not change the parameter value. while loop evaluate the parseInt of guess but it will now change it and prompt will assign to guess string, if you want only use parseInt in your case I recommand use it like this:

while (guess !== targetNumber){
if (guess > targetNumber) {
    guess = parseInt(prompt("Too high! Enter a new guess:"));
} else {
    guess = parseInt(prompt("Too low! Enter a new guess:"));
}

CodePudding user response:

Yes. Because it's block scope performance. In JavaScript if you declarat a variable with let, this is block scope. even for same variable name in new block like while and for is a new variable name so you need use parseInt inside while loop.

  • Related