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 trialEdgar Sánchez
2,649 PointsWhy does it not work like this?
I'm testing this on the console and it's pretty curious to me why if i copy and paste this code entirely:
var dieRoll = Math.floor(Math.random() * 6) + 1; alert("You rolled a " + dieRoll);
The code works as expected, but if I just type:
var dieRoll = Math.floor(Math.random() * 6) + 1;
and hit enter and then run the alert("You rolled a " + dieRoll); command it always gives me same result. What is the explanation of this behavior?
Thnx
3 Answers
Chyno Deluxe
16,936 PointsHey Edgar,
What is happening here is that you are saving a random number to the variable once.
var dieRoll = Math.floor(Math.random() * 6);
That being said, if the random number was 4 then the variables value will always be 4 until it is overwritten.
But, when you call the full script
var dieRoll = Math.floor(Math.random() * 6) + 1; alert("You rolled a " + dieRoll);
you are essentially overwriting any previous value of dieRoll. Thus giving you a different value every time you run the script.
I hope this helps.
TJ Nuccio
5,036 PointsHi Edgar,
I'm having a little trouble understanding the problem here exactly.
As you have specified:
var dieRoll = Math.floor(Math.random() * 6) + 1; alert("You rolled a " + dieRoll);
results in a different number each time the browser is reloaded.
I'm having a little trouble understanding exactly what problem you're having based off of your second code snippet (var dieRoll = Math.floor(Math.random() * 6) + 1;). It seems to me that these two code snippets are exactly the same with the exception that you didn't include the alert in the problem-code example.
If you run:
var dieRoll = Math.floor(Math.random() * 6) + 1;
your going to want to make sure you have an 'alert' statement directly following it as you do in the first code example that you've posted.
Please let me know if you're still having problems!
Edgar Sánchez
2,649 PointsThanks TJ Nuccio, I think I already understood what's happening!!
Edgar Sánchez
2,649 PointsEdgar Sánchez
2,649 PointsYes I understood it only after testing it like zillion times hahaha.
Thanks Chyno, great explanation!
Chyno Deluxe
16,936 PointsChyno Deluxe
16,936 PointsGlad I could help.