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

Javascript - Loop - For vs While

Hi there,

I have understand more clearly the concept of "for." But how to understand what's within this ( ; ; )? Because from the Quiz, I don't know how to interpret the asked question (var i=0; i<10; i=i+1) but can only guess its closest format based on the video from Jim.

Thanks!

The for-loop executes your code within the curly braces as long as what's inside the () is true. So for your example:

for(var i = 0; i < 10; i = i+1){ //some code here }

The first thing that happens is that the variable i is set to 0; the second thing (i <10) is that the for-loop will continue to do something (iterate) as long as i is less than 10. The loop then performs the code between the {}, and after that it adds 1 to the variable i (i=i+1). So now i has the value of 1 which is still less than 10, so the code between the {} will execute once more. And so again it adds 1 to i, which makes i 2. This will go on for as long as i is less than 10, if that is no longer true the for loop exits and your for-loop is done doing whatever it was supposed to do...

Hope that's clear enough, I have to run to a dentist appointment so this was written in haste, but I'll try to clarify if need be..

1 Answer

Hey Ann,

The for loop looks quite complicated, but it's actually pretty simple. The semicolons separate it into 3 parts(setting the variable, setting the condition, and updating the variable). I'll read it to you like an english statement.

(var i=0; i<10; i=i+1) -- Create a variable called i and set it to a value of 0; as long as the variable i is less than 10, run this loop; each time the loop is run, add 1 to variable i.

Basically, this is a loop that will run the code that is in the following block 10 times. For example:

for (var i=0; i<10; i=i+1) {
    console.log(i);
}

The previous code is a for loop that executes the contained block of code 10 times. It will log out the numbers 0-9 to the console.

Thanks Samuel and Henrik! : )

Glad to help.