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

MICHAEL COOK
MICHAEL COOK
7,248 Points

getRandomNumber is not defined

I tried to run the following code in my browser while going along with the video and the page showed up as blank. So when I inspected the page and went to console i got this message : app.js:2 Uncaught ReferenceError: getRandomNumber is not defined at app.js:2

this is the code:

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

function randomNumber(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>")

I can't figure out where I messed up because it all looks accurate and like I followed along in the video...

2 Answers

Stephen Fowles-White
Stephen Fowles-White
10,457 Points

Hi Michael,

When you declare the variable:

var randomNumber = getRandomNumber( upper )

You are calling the function getRandomNumber with the variable upper in it. But the function on the above code is

function randomNumber(upper) not getRandomNumber( upper ). You just need to make these function names the same and it should work.

This code worked for me.

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>")

I hope this helped

Stephen

MICHAEL COOK
MICHAEL COOK
7,248 Points

Thank you for the help with that, i just don't understand why the original code i posted worked for him in the video, but not for me. Either way, again, I appreciate the help!