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 trialAdriano Provenzano
2,144 PointsRandom number in js
why is my browser showing me the random number as undefined?
3 Answers
Steven Parker
231,268 PointsAre 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!
Joseph Wasden
20,407 PointsAre 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.
Joseph Wasden
20,407 PointsYou 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);
Adriano Provenzano
2,144 PointsAdriano Provenzano
2,144 Pointsvar 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
231,268 PointsSteven Parker
231,268 PointsOh, 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).