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 What are Loops?

Carolyn Scudder
Carolyn Scudder
1,760 Points

My code won't work when I preview in Chrome browser, but it will when I cut and paste it into console...

Hello! I'm a JavaScript newbie so really could use some help. Lately when I try running my code that I'm working on from workspaces the only thing that shows up is the Title from the HTML but the code doesn't actually appear to run. Here is what I'm trying to run right now...

function randomNumber(upper) {
  return Math.floor( Math.random() * upper ) + 1;
}
var counter = 0;
while (counter < 100) {    //this code states that as long as the count variable is less than 10 to keep running the loop
  var randNum = randomNumber(6);
  document.write(randNum + ' ');
  counter += 1;        //this code states to add 1 after each loop
}

HOWEVER; when I open up the console and cut and paste the code in there it will show the random numbers I asked for but not the HTML Heading.

Can someone please tell me what I'm doing wrong? Thanks!

3 Answers

L B
L B
28,323 Points

I was testing your code and it runs fine. Just revised it for my own testing:

function randomNumber(upper) {
    return Math.floor(Math.random() * upper) + 1;
}
var counter = 0;
while (counter < 10) {
    document.write(randomNumber(6) + ' ');
    counter ++;
}

Have you included the js file in your html file? Or have you included it correctly?

<script src="myscripts.js"></script>

Change myscript.js to your js file name. Make sure you get the name right and its in the same folder.

maryam aljimaz
maryam aljimaz
8,051 Points

Did you include the .js file within the html file. You should be able to see something like this in the html index file.

<script type="text/javascript" src="YOUR JS file"></script>
Carolyn Scudder
Carolyn Scudder
1,760 Points

Thank you for your replies! Simple mistake, I was using a workspace from a different video so the js file did not link correctly. Thanks for your help! :D