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 JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge Solution

J V
J V
3,414 Points

Why do I not receive the correct output for the Random Number Challenge using Global Variables?

Below is my JavaScript code. The output provided is not between the user's specifications and I do not know why? Is there something that I am overlooking in the code?

var userMin = prompt("Enter the minimum number");
var userMax = prompt("Enter the maximum number");

var differential = userMax - userMin;

function calculateRandom(userMin,userMax)
{
  var number = Math.floor(Math.random() * (differential + 1)) + userMin;
  return number;
}

console.log(calculateRandom(userMin, userMax));

1 Answer

akak
akak
29,445 Points

Hi,

Prompt is giving you back a string, not a number. So you're trying to add, for example "3" + "5" which gives "35" not a number 8. Use parseInt before each prompt to get correct values

var userMin = parseInt(prompt("Enter the minimum number"));
var userMax = parseInt(prompt("Enter the maximum number"));