Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Leandro Gomes Silva e Silva
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Leandro Gomes Silva e Silva
Full Stack JavaScript Techdegree Graduate 17,514 Points

Two different methods which should produce the same outcome. What is wrong in this code?

Hello community,

Would you kindly support me with the following problem? The code that I wrote is these:

/**

  • Returns a random number between two numbers. *
  • @param {number} lower - The lowest number value.
  • @param {number} upper - The highest number value.
  • @return {number} The random number value. */

function getRandomNumber(lower, upper) { const RandomNumber = Math.floor( Math.random() * (upper - lower + 1) ) + lower; return RandomNumber; }

// 1st method: Calls the function by writing the two arguments directly in the code ==> Outcome: plausible! console.log(getRandomNumber(20,100));

// 2nd method: Asks the user for input and assign it to the function ==> Outcome: completely wrong.

const lower = prompt(Enter the lower number.);

const upper = prompt(Enter the upper number.);

console.log(getRandomNumber(lower,upper));

Why does the 2nd method is returning totally weird values? If I insert for example 20 and 100 via "prompt", I get a number between like 410 or 1020.

Could somebody explain to me why this is happening?

Thank you very much in advance.

2 Answers

Steven Parker
Steven Parker
231,140 Points

Values returned by "prompt" are strings, not numbers. Convert them into numbers before doing math on them:

const lower = parseInt(prompt("Enter the lower number."));
const upper = parseInt(prompt("Enter the upper number."));
Leandro Gomes Silva e Silva
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Leandro Gomes Silva e Silva
Full Stack JavaScript Techdegree Graduate 17,514 Points

Thank you a lot Steven. I can verify it by using "typeof(RandomNumber)". I completely forgot that prompt return strings. Well, I think this is what learning is about. I'm sure I'm not forgetting it again. Thank you very much!!