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 trial

JavaScript

for loop execution technicality

I have a quick question about 'for' loops. Here is the code taken from one of the lessons:

for (var counter = 10;counter; counter = counter - 1) {
    console.log("Hello World", counter);
}

Is it just understood that the 'counter' variable declaration will only get run once in a for loop? In an initial examination, I would have expected counter to get set to 10 on each loop execution.

Therefore 'counter' would never get to be less than 9, and it would be an infinite loop. Can anyone explain why the 'var counter = 10' gets skipped over on subsequent executions of the loop?

1 Answer

The formatting of the statements in the parentheses of a for loop are as follows

for(/*Initial variable assignment that only runs once*/; /*Condition that will determine if the loop runs each time*/; /*Event that should occur when each iteration is run that could change the condition*/){
    //Looping code here
}

Thus, the for loop you described looks something like this (with minor code readability improvements): <pre>

/*                 Condition that checks
                    if counter is not falsey
                       (i.e. not 0)
                     (checked every time)
   Initial assignment      |     Decrements the counter variable
        (runs once)        |       (runs every time)
                   |       |          |                    */
for (var counter = 10; counter; counter--) {
    console.log("Hello World", counter);
}

</pre>

Awesome, thanks for the very clear explanation and quick response!

No problem! Sorry for the unpredictability of the lines in the last code block, by the way. I think I fixed it!