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

Edgar Sánchez
Edgar Sánchez
2,649 Points

Why 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

Hey 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.

Edgar Sánchez
Edgar Sánchez
2,649 Points

Yes I understood it only after testing it like zillion times hahaha.

Thanks Chyno, great explanation!

Glad I could help.

TJ Nuccio
TJ Nuccio
5,036 Points

Hi 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
Edgar Sánchez
2,649 Points

Thanks TJ Nuccio, I think I already understood what's happening!!