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

Andrico Karoulla
seal-mask
.a{fill-rule:evenodd;}techdegree
Andrico Karoulla
Front End Web Development Techdegree Student 13,760 Points

An error with the output of this code

alert("Welcome to my random number generator, this program will pick a random number between the 2 numbers you select.");

var x = parseInt(prompt("Pick a number."));
var y = parseInt(prompt("Pick a second number."));

function getRandomNumber(x, y) {
    if (x > y) {
    var randomNumber = Math.floor( Math.random() * (x - y + 1) + x);
    return randomNumber;    

    } else if (x < y) {
    var randomNumber = Math.floor( Math.random() * (y - x + 1) + y);
    return randomNumber;    

    } else {
    alert("Invalid Selection");
    }
}
alert(getRandomNumber(x, y));

2 Answers

jrabello
jrabello
17,917 Points

Hello,

That's why using letters for variable names are dangerous, it should be using something like

Math.floor(Math.random()*(max-min+1)+min);

change x and y variable names and you should see your error in 1 second

ahmed suleiman
PLUS
ahmed suleiman
Courses Plus Student 11,685 Points

Look at the first if statement the min is y thus you should add y instead x and vice versa the next the min x you should add x instead of y