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) Working With Numbers Create a random number

Can't see any error, but random number generator won't work?

I used the following code:

var dieRoll = Math.floor(Math.random() * 6) + 1; dieRoll;

The final result always returns 3 as the "random number". The random generator does not work. Any advice?

2 Answers

Alan Jaffery
Alan Jaffery
4,803 Points

Just checked my self. With this code it works: var dieRoll = Math.floor(Math.random() * 6) + 1; alert(dieRoll);

Try it your self. After refreshing the page i got always another (random) number

Even with this code, if I run the first part, create a random number and store that to the variable. Then press enter, it provides an undefined variable. Then run the next line of code alert=(dieRoll), and still gives a single value and doesn't change each time the variable is called. Your code returns 6 each time.

Thank-you for the clarification

Alan Jaffery
Alan Jaffery
4,803 Points

No problem. Hope i could help you :)

That is the full code. It was a test run to see how random numbers work. I created the variable dieRoll then added the Math.floor and Math.random functions, and finally called the variable dieRoll to provide the answer, like this:

var dieRoll = Math.floor(Math.random() * 6) + 1; dieRoll;

Strange enough, I tried running the above code as it is on console.log in chrome, and it works perfectly fine, however, if I try to run the random number by storing the number in the variable dieRoll pressing enter (which gives me undefined as a result), and then try to run the dieRoll; as a separate command on the next line, it gives me the same number each time, 3 as the result.

Alan Jaffery
Alan Jaffery
4,803 Points

Thats because the variable is !once! filled and after that not changed anymore. Due to that each to giving out the content of the variable will be the same over and over. you would need to set it each time new to get other numbers. try the code i answered. With that the random number will always apear newly

kind regards & sorry for my bad english :) alan