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!

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 Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1 Solution

Is 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

The var is indeed optional. Some people just consider it better practice to leave it in.


Ezra Siton
Ezra Siton
12,644 Points

You 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";

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

Thanks for the added info on this topic/issue!