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 trialfurkan
11,733 PointsCan'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
4,803 PointsJust 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
furkan
11,733 PointsEven 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.
furkan
11,733 PointsThank-you for the clarification
Alan Jaffery
4,803 PointsNo problem. Hope i could help you :)
furkan
11,733 PointsThat 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
4,803 PointsThats 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
Sharina Jones
Courses Plus Student 18,771 PointsSharina Jones
Courses Plus Student 18,771 PointsCould you please post your full code?