for LoopsWe sometimes do some work repeatedly in our daily life; like a student may be told to do an assignment three times :) etc. For human beings repeating something is tiring as well as boring. But for computers, it is not. And telling a computer to do something repeatedly is as easy as saying "ABC". Believe me.
One of the keywords in JavaScript that we can use to tell the computer to repeat something is "for" - sometimes called a for loop. Its basic syntax is shown below:
for (initialization; test_condition; change)
{
// do something
}
Note a few things: the statements that we want to be executed repeatedly are enclosed between { and }. The starting part of the loop defines how many times the loop will be executed. If we want to say that do this four times, we will write for (i=0; i<4; i=i+1). I know its difficult to digest, but it is not that bad.
The first part says, "set i=0". You must be quite comfortable with that if you have studied elementary algebra. Next we have a test condition: i<4, which is certainly true (because we just set i equal to zero). Thus the body of the loop (i.e. the part in the braces { and }) will be executed. Once all the code has been executed, the computer performs the change part: i=i+1. This part is the most difficult to understand (if it is). It says, "set i equal to i+1". Since i was zero in the beginning, the first execution of this "change" part will set i equal to zero plus one (i.e. 1). After that the "test_condition" (i.e. i<4) will be checked. Since 1 < 4, the body of the loop will be again executed (second time). This process continues until i becomes 3. When that happens, the body of the loop will be executed once more and after that i becomes 3+1, that is 4. When the condition will be checked this time, 4<4 is false. Thus, the loop will end.
An ExampleLet's do an example to clarify the things. We will revert to our favorite phrase, "Hello World!". Suppose we want to display this text 15 times on a web page. Doing this thing in plain HTML will require typing "Hello World!" 15 times. But then why is JavaScript for. We will take help from the write property of the document object (see one of the previous articles):