www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons JavaScript for Loop Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
Lesson 45
Lesson 46
Lesson 47
Lesson 48
Lesson 49

There are occassions when we need to run some part of our code more than once. Duplicating or copy pasting the code to run multiple times is not efficient and elegant. JavaScript provides us with a number of looping constructs to achieve this.

In this lesson we will learn the simplest of the JavaScript loops i.e. for Loop.

Formally speaking loop constructs in JavaScript are used to executed the same block of code a specified number of times or till a specified condition remains true.

A for loop keeps repeating until the loop condition remains true. A for loop in JavaScript is very similar to the Java, C and C++ for loops. Its syntax follows:

for ([initialExpression]; [condition]; [loopControlExpression]) {
//code to be executed / repeated
}

A for loop executes in the following sequence:

1. The optional initializing expression initialExpression is executed. This expression is generally used to initialize a loop counter variable.

2. The optional condition expression is evaluated. If the value of condition is the code of the loop is executed / repeated otherwise the for loop immediately terminates. In case we do not provide a condition, it defaults to true.

3. The loopControlExpression is executed. The loopControlExpression is generally used to increment or decrement the loop counter variable. The control then transfers to the step 2 above.

Example code follows:

<html>
<body>
<script type="text/JavaScript">
var i = 0;
for (i=0; i<=5; i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The above code executes the for loop body 5 times.


Next >>> Lesson No. 12: JavaScript while Loop







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.