Loops and Iterations in JavaScript

SEARCH THIS SITE

Custom Search



A loop in javascript is used for repeated operations. Arrays are also suitable to be used within loops.

The For loop

In the javascript example program 1 below, the set of statements shown below
for (i = 0; i < 5; i++) {
sum = sum +i;
}

is used to calculate the sum of the numbers: 0, 1, 2, 3 and 4. It is also called a loop ans each step of the loop is called an iteration.
This is done through the steps:
1) i = 0; , this is done before the loop starts.
2) i < 5; , checks if i is less than 5 before the llop starts.
3) i++; , increments i by 1 after each iteration. (i++ has the same effect as i = i + 1)
and finally the statement sum = sum +i; is the block of code to be executed at each iteration. It could be more than one statement.

Javascript Example Program 1

<!DOCTYPE html>
<html>
<body>
<script>
var i;
var sum = 0;
for (i = 0; i < 5; i++) {
sum = sum + i;
}

alert(sum);
</script>
</body>
</html>

The While Loop

In the javascript example program 2 below, the set of statements
while (j < 6) {
sum = sum + j;
j++;
}

is called a while loop. Starting with sum = 0 and j = 0, the loop calculate the sum of 0, 1, 2, 3, 4 and 5 using the statement sum = sum + j; . At each iteration, j is added to the sum while j and is incremented (j++). When j becomes greater than or equal to 6 (because of the incrementation), the iteration process stops.
Run the sample program below and check that the answer displayed is 15. ( 0 + 1 + 2 + 3 + 4 + 5 = 15 )

Javascript Example Program 2

<!DOCTYPE html>
<html>
<body>
<script>
var sum = 0;
var j = 0 ;
while (j < 6) {
sum = sum + j;
j++;
}

alert(sum);
</script>
</body>
</html >

Arrays and Loops in Javascript

One of the most efficient use of arrays is within a loop. In example program 3 below, we define two arrays x and y with 6 values each: x: 0,4,5,7,8,9,12 and y: 1,2,3,6,8,10,12. The statement var leng = x.length; is used to find the number of elements of the array. The while loop is here used to find the sum Σ x[i]*y[i] for i = 0 to i = leng - 1. (-1 is due to the fact that the index of an array starts at 0).
Run the sample program below and check that the answer displayed is 363. ( Σ x[i]*y[i] = 0*1 + 4*2 + 5*3 + 7*6 + 8*8 + 9*10 + 12*12 = 363 )

Javascript Example Program 3

<!DOCTYPE html>
<html>
<body>
<script>
var x = [0,4,5,7,8,9,12];
var y = [1,2,3,6,8,10,12];
var leng = x.length;
var sum = 0;
var j = 0 ;
while (j <= leng - 1) {
sum = sum + x[j]*y[j];
j++;
}

alert(sum);
</script>
</body>
</html >


Books and References

1 - A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your effort in half - Mark Myers
2 - A Smarter Way to Learn HTML & CSS: Learn it faster. Remember it longer. (Volume 2) - Mark Myers
3 - http://www.w3schools.com/js/default.asp - JavaScript Tutorial