Lesson 11: The For Loop



The For Loop:

The for loop is used primarily when you have a block of code that needs to be executed a certain number of times and you know the number of times it needs to be done.


Syntax:

for (var=startValue;var<=endValue;increment) { Code to be executed }


*Note: You may have noticed that I have a somewhat different style of using the curly brackets ({}) than most coders. I like to place my first curly bracket on the same line as the statement, so the code can be started on the next line. Most examples you will see online will use a whole line for this bracket. How you do this is completely up to you. As I explained in the beginning of the tutorial, JavaScript is a loosely typed language, so you can use spaces or break your lines where you like in most cases. I use two spaces before my first {, but you may decide to do this different. But you should do it similar to how you see it done commonly, so your code can be understood by others. The way I do it is not the most common way, but it is a way used by many.


Example code:

var i=0;

for (i=0;i<=10;i++) {

document.write(i + " times<br>");

}


Code explained: In the first line, we declared the variable i and set it to 0. Then on line 2 we start the for loop. We say i=0 for the starting value then we say <=10 which means less than or equal to 10, where 10 is our end value. Then we say i++ which increases the value of i by 1. On line three, we say write to the document, the value of i and concatenate the word “time” and a HTML line break to it. Then on the last line, we have our end curly bracket to indicate that the code to be executed is over and to return to the line 2 where the for loop starts again as long as the value of i is less than or equal to 10.


Okay that is about it for our Beginner’s JavaScript Tutorial. Congratulations, you have learned the basics of JavaScript. In the next couple of chapters we will go over some things that were not covered yet, but that have been demonstrated a bit. In lesson 12 we will go over the most common operators and in the final lesson, we will cover reserved words so you can have them for reference. There is always more to learn, but we have covered everything that is generally considered to be at a beginner’s level. To continue learning more JavaScript, watch out for my intermediate tutorial that will be coming out soon.


You may proceed to the next lesson. In lesson 12 we will discuss the most common operators used in JavaScript:

                    

Copyright © 2012 VisualBuilder. All rights reserved