JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Morgan Walstrom
Morgan Walstrom
4,683 Points

Where is the function being invoked?

var upper = 10000; var randomNumber = getRandomNumber(upper); var guess; var attempts = 0;

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

while( guess !== randomNumber ){ guess = getRandomNumber( upper ); attempts += 1; } document.write("<p>The random number was: " + randomNumber + "</p>"); document.write("<p>It took the computer " + attempts + " attempts to get it right.</p>");

2 Answers

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,609 Points

Morgan Walstrom , you can see in 2nd line of your code i,e :

var upper = 10000;
var randomNumber = getRandomNumber(upper);      // Function getting invoked here
var guess;
var attempts = 0;

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

while (guess !== randomNumber) {
  guess = getRandomNumber(upper);
  attempts += 1;
}
document.write("<p>The random number was: " + randomNumber + "</p>");
document.write("<p>It took the computer " + attempts + " attempts to get it right.</p>");

So , you can see in 2nd line , function is getting invoked and the retured value gets stored into the variable randomNumber.
Actually this is called Hoisting .
In JavaScript , both functions declaration and function definition get hoisted.
In other words , JavaScript interpreter allows yo to use the function before the point at which it was declared in the source code. Hope it help :)

Morgan Walstrom
Morgan Walstrom
4,683 Points

I thought so, I just have never invoked a function that was being stored in a variable. var upper = 10000; var randomNumber = getRandomNumber(upper);
so on line 2 is the parameter the variable on line one? upper is getting passed in? cool way to do it just new to me!

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,609 Points

Actually , the function is not stored in a variable . What's going on is -
We are calling the function first , then storing it's value in a variable . So ,it's the value that gets stored not the function itself. Remember ,whenever a function returns a value , we want to store that value in some variable so that we can use that value.
Same thing is going on here , function is returning a value and we are so storing that value in a variable in line 2.

Morgan Walstrom
Morgan Walstrom
4,683 Points

Thanks that makes a lot of sense!

Ivy Garrenton
Ivy Garrenton
3,761 Points

So we can call a function before the function is written in the script?

We can call a function before it is declared yes, that's hoisting as Aakash said above, although we can call a function we can't call a function expression. You should avoid hoisting as much as possible. Things could get really complicated really fast.