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 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.

Thanks!

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

Thanks for the added info on this topic/issue!