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

Adriano Provenzano
Adriano Provenzano
2,144 Points

Random number in js

why is my browser showing me the random number as undefined?

3 Answers

Steven Parker
Steven Parker
231,271 Points

Are you typing this into the console?

Math.random()

If you're doing something else, show your exact code here for analysis.

And if you are typing exactly that into the console and getting "undefined" — I recommend you try a different browser!

Adriano Provenzano
Adriano Provenzano
2,144 Points

var question= prompt("What's your favorite number?"); var number = parseInt(question); var sentence = "Your favorite number: " + number; sentence += " means....." + random; var random = Math.floor(Math.random()*2)+1;

document.write(sentence);

It is a stupid example but it should work...

Steven Parker
Steven Parker
231,271 Points

Oh, that's just a matter of the order of execution. You referenced "random" on the line before it was assigned, so at that moment its value is literally "unassigned".

Just swap the order of that line and the one that assigns it and you'll get a numeric result (either 1 or 2 based on that formula).

Are you assigning a variable a value? If you assign a variable a value, it will return the current value of the variable before performing the assignment. So, it will seem as if it has assigned it undefined. However, it will have completed the assignment after having returned the current value. See the image below.

https://imgur.com/peEvBSr

You aren't assigning random before trying to use it to assign to sentence.

        var question = prompt("What's your favorite number?"); 
        var number = parseInt(question); 
        var random = Math.floor(Math.random()*2)+1; // moved up in code to resolve assignment before use in sentence assignment.
        var sentence = "Your favorite number: " + number; sentence += " means....." + random; // now we can get a value for random other than undefined, since we defined it.

        document.write(sentence);