## Javascript TUTORIAL

### For Loop

The for loop is useful when we want to execute the same statement for a large number of times. Let us assume that we want to covert degree fahrenheit into degree celcius.
The formula for cooverting degree celcius into degree fahrenheit is

C = 5 * (F-32)/9

Let us assume that we want to calculate and print the value of the degree Celcius for values of degree fahrenheit from 31 to 40. We can do it as shown in the example below.



The program will produce the desired result. However, the same statement is repeated again and again. In such case the for loop is used. Let us write the same program using a for loop.



Inside the for loop, enclosed in brackets ( ), we initialise the variable F to 31. The condition (F <=40) is then evaluated. Since F is less than equal to 40, the statements inside the for loop are executed.

After executing the statement, the javascript executes the statement F++,which increases the value of F to 32. It then again test the condition (F<=40). Since it is true again, the statements inside the for loop is executed again.

This goes on till the value of F becomes larger than 40. At this point, the statement immediately following the for loop is executed.

We have defined a function which will calculate the area of the rectangle. Let us take a look at the fuction again.

You can try this example online at the link below, which will open in a new window.

Javascript for loop - Example

Having looked at the example, let us take a look at the formal definition of the for loop.

for (Initialization statements; Condition; Updation statements)
{
...
statements
...
}

When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the condition. Only when the condition returns 'true', the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns 'false' and the loop stops. Some important points to note are:

* The initialization statements are executed once; only when the for loop is encountered.
* After execution of initialization statements, the condition is evaluated.
* After every iteration, the updation statements are executed and then the condition is checked.