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 trialjomclaughlin
8,720 PointsIs the var in for loop (var i = 0) optional? Have noticed the code still runs when I forget it...
For example, this for loop still ran without errors when I did this quiz challenge:
for ( i = 0; i < quiz.length; i += 1 )
I have not defined 'i' anywhere else in the code.
2 Answers
Travis Howk
7,169 PointsThe var
is indeed optional. Some people just consider it better practice to leave it in.
Ezra Siton
12,644 PointsYou are wrong Only in the context of the Q. This is not a specific "for-loop " issue, but general JS issue.
This code is OK (You won't get compile error. But this is bad practice)
name = "john";
alert(name);
If you really want to read about this issue see this Q on stackoverflow: https://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional
jomclaughlin
8,720 PointsThanks for the added info on this topic/issue!
jomclaughlin
8,720 Pointsjomclaughlin
8,720 PointsThanks!