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 trialAviral Gupta
5,586 PointsWe 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
45,783 PointsAviral,
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
45,783 PointsAviral,
Can you post the code that you're having difficulty with?
Erik
Aviral Gupta
5,586 Pointscheck now
Aviral Gupta
5,586 PointsAviral Gupta
5,586 Pointsthanks that helps :)