Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops What are Loops?

Aviral Gupta
Aviral Gupta
5,586 Points

We are declaring the randomNum variable again and again in loop? Is it ok?

Pls help me out!

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

var counter = 0; while( counter<10 ) { var randNum = randomNumber(6); // Why is this variable being declared again and again in loop in video?? document.write(randNum + ' '); counter += 1; }

2 Answers

Erik McClintock
Erik McClintock
45,782 Points

Aviral,

In this instance, it doesn't really matter where the variable is declared, as JavaScript does not have what's known as "block scope". My guess is that Dave declared this variable inside his while loop because that's the only place he needs it, so it could just be as a reminder/good practice (since JavaScript DOES have function scope, so perhaps it's just a way to remember to declare things where they're needed to make your code efficient and safe). It is okay for the variable to be redeclared like this, though I don't believe that there is any particular technical need for it one way or the other.

Erik

Erik McClintock
Erik McClintock
45,782 Points

Aviral,

Can you post the code that you're having difficulty with?

Erik