Higher or lower exercise


#1

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.


#2

we can visualize the problem:



function guessNumber(number) {
// Prompt the user for a number
guess = prompt("Guess a number between 1 and 100");
alert(typeof(guess));
// 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)


#3

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


#4

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

https://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript
https://stackoverflow.com/questions/17106681/parseint-vs-unary-plus-when-to-use-which


#5

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