# Higher or lower exercise

Here’s a code from “Higher or lower?” exercise:

function guessNumber(number) {
// Prompt the user for a number
guess = prompt(“Guess a number between 1 and 100”);

// Convert their guess to a number using +
guess = +guess;

// Define base case
if (guess === number) {
return console.log("You got it! The number was " + number);
}
// Define recursive case with a function call
guessNumber(number);
}

// Call the function guessNumber() with an integer for an argument
guessNumber(26);

Can someone please explain more elaborately what line “guess = +guess;” does and why doesn’t the program work without it (I’ve tried using a positive number as a guess)? I don’t quiet understand the explanation in the code. Why we should convert user’s guess to a number if he already passed one? How ‘+’ makes that job? etc.

we can visualize the problem:

``````

function guessNumber(number) {
// Prompt the user for a number
guess = prompt("Guess a number between 1 and 100");
// Convert their guess to a number using +
guess = +guess;

// Define base case
if (guess === number) {
return console.log("You got it! The number was " + number);
}
// Define recursive case with a function call
guessNumber(number);
}

// Call the function guessNumber() with an integer for an argument
guessNumber(26);
``````

typeof returns the data type, which is string.

`if (guess === number)`, you use three equal signs which mean data type needs to match (26 is integer, while the user guess is string)

1 Like

ok, thanks! got that. how ‘+’ converting it to a number then?

It seems to a javascript named unary plus, i found some stackoverflow questions:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.