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

Why does "var randomNumber = getRandomNumber(upper)" require "upper" to be listed in this value assignment?

Why can you not just write "var randomNumber = getRandomNumber()"? If upper is in the function:

var upper = 10000;

function getRandomNumber(upper) { return Math.floor ( Math.random() * upper ) + 1; }

Any clarity on this is much appreciated :)

1 Answer

Steven Parker
Steven Parker
243,318 Points

The value passed to the function represents the highest possible number.

The function will generate a random number between 1 and the value you pass to it. That's what "upper" does in the formula when it is multiplied by Math.random().

If you were to call getRandomNumber() with no argument, the math formula would fail and return "NaN" (not a number).

It doesn't matter if you have defined a variable outside the function with the same name "upper", since inside a function, arguments always override global variables.

You could, however pass "upper" as the argument when you make the call, as in your first example.

If I understand correctly:

Global variable "upper" has not been assigned as an argument to the function unless you say "getRandomNumber(upper)"?

If you say "getRandomNumber()" the "upper" variable in the function does not have a value assigned so it becomes NaN?

Steven Parker
Steven Parker
243,318 Points

Close. If you call "getRandomNumber()" passing no argument the "upper" variable inside the function is undefined. Then, when the calculation made using the undefined value fails, it returns NaN as the result.