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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Aaron Selonke
Aaron Selonke
10,323 Points

This variable comes back as undefined, Alert message is 'undefined' not an error???

var Num; function OriginalRandomNumber() { Num = Math.floor( Math.random() * 10000 ) + 1; }

alert(Num);

This is not a universal scope variable, right? Why does the alert message come back as undefined?

2 Answers

Erwin Meesters
Erwin Meesters
15,088 Points

First you declare a variable called Num, without a value. So it's undefined at this stage. Then you declare a function called OriginalRandomNumber which takes the variable Num and sets it's value to a random number. Without calling the function nothing will happen and the variable Num will stay undefined. So you have to call the function.

var Num; 
function OriginalRandomNumber() { 
  Num = Math.floor( Math.random() * 10000 ) + 1; 
}
OriginalRandomNumber();
alert(Num);
Aaron Selonke
Aaron Selonke
10,323 Points

Cheers! Calling the function helps.

The variable was declared outside of the function to keep it's scope universal.