Page 100 - PortGPT_V2.1_C8_Flipbook
P. 100
Here,
• initialisation_expression: In this expression, a variable is initialized which is also known as loop
control variable. This expression is executed only once in a loop.
• conditional_expression: This expression contains a logical condition which returns either True
of False. If the condition evaluates to True, the statements written inside the loop body will
execute. If the condition evaluates to False, the statements written inside the loop body will be
skipped. Loop will terminate once the condition becomes False.
• update_expression: This expression is executed after every pass of the loop. A pass of a loop is
known as an iteration. In this expression, the loop control variable is updated by increasing or
decreasing its value.
• Loop body: This section contains the statements that are to be executed repeatedly enclosed
whin the curly braces.
Ensure that every expression should be terminated with a semicolon in the for loop, otherwise an
error will occur.
For example,
for(i=0; i<5; i++)
{
document.write(i);
}
In the preceding code, you can see that the variable i is initialised with the value 0. Next, a logical
condition i<5 is evaluated and returns True as the value of i is less than 5. After this, the variable i
is increased by 1 with the help of increment operator. In the body of the for loop the value of i is
printed. When the loop is executed once, the value of the variable i becomes 1 which is still less than
5. So, the loop will execute again and again until the value of the variable i becomes 5 and displays
the value of variable i every time. Let us use the for loop in a web page.
Program 1: To create a web page that displays the table of 2 using for loop in JavaScript.
<HTML>
<HEAD>
<TITLE> Using for Loop </TITLE>
</HEAD>
<BODY>
<H2> Using for Loop to Display the Table of 2 </H2>
<SCRIPT>
var n=2;
for(var i = 1; i <= 10; i++) {
var result = n * i;
document.write(n + " x " + i + " = " + result+"<BR>");
}
98 Premium Edition-VIII

