Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

Using loops in JavaScript

6 Mar 2014

The main strength of any programming language is its ability to process blocks of code
repeatedly. JavaScript, like other programming languages, provides us with loop.
Statements placed inside loops are executed a set number of times... or even infinitely.
Loops can be introduced by using any one of the three statements; for ,
while and do...while
Here is the format of a 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.
Displaying the 12 times table in an alert box
var msg = "";
var res = "0";
for (var x = 1; x <= 12; x++)
{
res = 12 * x;
msg = msg + "12 X " + x + " = " + res + "\n";
}
alert(msg);
Exercise 1: Create a script that calculates the average of 5 numbers entered by the visitor
through a prompt?
var msg = "";
var num = 0;
var sum = 0;
var avg = 0;
for (var x = 1; x <= 5; x++)
{
num = prompt("This script calculates the average of 5 numbers", "Number " + x);
num = parseInt(num);
sum = sum + num;
}
avg = sum / 5;
alert("The average of the 5 numbers is " + avg);

Exercise 2: Change the script above and make it more flexible. Ask the visitor for the
total number of numbers and then find the average.
var msg = "";
var num = 0;
var sum = 0;
var avg = 0;
var t = prompt("For how many numbers would you like to find the average?", "");
t = parseInt(t);
for (var x = 1; x <= t; x++)
{
num = prompt("This script calculates the average of 5 numbers", "Number " + x);
num = parseInt(num);
sum = sum + num;
}
avg = sum / t;
alert("The average is " + avg);
The JavaScript while loop is much simpler than the for loop. It consists of a condition
and the statement block.
while (condition)
{
...statements...
}
As long as the condition evaluates to 'true', the program execution will continues to loop
through the statements.
The do-while loop
You can consider the do-while loop as a modified version of the while loop. Here, the
condition is placed at the end of the loop and hence, the loop is executed at least once.
Exercise 3: Separating a Number into its Digits
while ( number > 0 )
{
digit = number % 10;
number = number / 10;
printf("%d \n", digit );
}

You might also like