For loops


I am really bad at for loops can any body explain to me how a for loop works


google search
== the Book ==
for loop

== discussions / opinions ==
javascript for loop


Hi @doggy11

A for loop is one of many loops used by coding languages in order to be able to repeat a bock of code for a certain amount of times.
The syntax for a for loop is made up of 4 parts. Parts #1, #2 & #4 are in the parens and are delimited by semi-colons, the final part, which is #3 is the code that is executed each run of the for loop.

        //#1                              #2                     #4
for (initiate the variable; evaluate the condition; increment variable) { 
        //the code block that occurs each run of the for loop #3

A brief overview of these parts is as follows:

  1. You declare and set a var that will be used in the for loop.
  2. You create a condition that will be evaluated by the for loop that will be used to tell the for loop to keep on running until this condition is no longer true. In short while the expression in #2 is always true the for loop will run, this is how infinite loops occur :wink:.
  3. Now this may look confusing however this is the process of for loops, they actually perform the code block at this time before they increment the initial variable set in #1. In here is what you want to happen, be it a print out to console of some value, an expression that is assessed or etc.
  4. The final part before we go back to #2, here the initial variable is incremented, and then is re-evaluated at #2 and if it is true it will step back in the code block and if false it will exit the for loop.

With this in mind lets look at a simple working example then.

for (var i = 1; i < 10; i++) { 
    console.log("When i == 9 it will stop; i is now at "+ i );

So we initiate the for loop at #1 and declare and assign a var i equal to a value of 1.
Now we are telling the for loop that so long as i is less than "<" 10 do something.
This something is to print a message to the console.log(), that includes a line of text and also the value of i, using concatenation "+" symbol.
Finally we increment i by 1 in the final part of the for loop parens with i++;

The key here is that we have set an expression that at some point can evaluate to false in #2, with i < 10, because each loop will increment i by 1 until the expression is no longer true.

Although CodeCademy does try to explain things as much as possible, I myself have also found that researching around sometimes yielded me a better understanding so be sure to use the internet on your coding journey.


thanks so much I think i understand now