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

shay r
shay r
11,337 Points

Random Number Function code Problem

Hello Everyone,

Why does my code below not produce an alert box with a random number?

randomrange(x,y) {

var randnum = Math.floor(Math.random() * (x - y + 1)) + y;

return randnum;

}

alert(randomrange(1,6));

1 Answer

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

There are few issue in your code -

  1. use the 'function' keyword i,e function randomrange(x,y){ .... }
  2. You always subtract a lower value from higher value and add the lower value . So , you should use :
    var randnum = Math.floor(Math.random() * (y - x + 1)) + x;
    Finally , your code should look like this :
function randomrange(x,y){
var randnum = Math.floor(Math.random() * (y - x + 1)) + x;
return randnum;
}
alert(randomrange(1,6))