INFORMATION SHEET NUMBER 3.
Decisions, Loops, and Functions
LOOPING – The for and while Statements
Looping means repeating a block of code while a condition is true. This is achieved in JavaScript
using two statements, the while statement and the for statement.
The FOR Loop
The for statement allows you to repeat a block of code a certain number of times.
Syntax Form:
Initialize loop variable Loop test condition Increment loop variable
for (loopCounter=1; loopCounter<=3; loopCounter++)
{
// execute this code
}
Code looped through
The for loop statement is almost the same to the switch statements it also has its logic inside
parentheses, but in the for loop statement the logic is divided into 3 parts, and each part is separated
by a semicolon.
The first part of the for statement’s logic is the initialization part of the for statement. Use to keep
track of how many times we have looped through the code.
The second part is the test condition. The code inside the for statement will keep executing for as
long as this test condition evaluates to true. The number of times a loop is performed called the
number of ITERATIONS.
The last part is the increment part, where variables on our loop’s test condition have their values
incremented. The ++ operator is used to increment the value by one. This part of for statement is
repeated with every loop of the code. Again this part of the for statement is repeated with every loop
of the code. Although we call it increment part, it can actually be used to decrease or decrement the
value.
After the for statement, we have the block of code that will be executed repeatedly as long as the test
condition is true. This block of code contained within curly braces. If the conditions is never true, even
at the first test of the loop condition, then the code inside the for loop will be skipped over and never
be executed.
Putting all the above together, how does the for loop work?
1. Execute initialization part of the for statement.
2. Check the test condition. If true, continue if not exit the for statement.
3. Execute code in the block after the for statement
4. Execute the increment part of for statement
5. Repeat steps 2 to 4 until the test condition is false.
Try It Out – for Loop
1. <HTML> 2. <HTML>
<BODY> <BODY>
<SCRIPT LANGUAGE = "JavaScript"> <SCRIPT LANGUAGE = "JavaScript">
var a; var a, b;
for (a = 0; a<=10; a++) for (a = 1; a<=3; a++)
{ {
document.write(a); document.write("a");
} for (b = 1; b>=5; b++)
</SCRIPT> {
</BODY> document.write(b + "<BR>");
</HMTL> }
}
</SCRIPT>
</BODY>
</HMTL>
3. <HTML>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
var a, b;
for (a = 1; a<=3; a++)
{
document.write("a");
for (b = 1; b<=5; b++)
{
document.write(b + "<BR>");
}
}
</SCRIPT>
</BODY>
</HMTL>
The for…in Loop
The for…in loop was introduced in JavaScript version 1.3. This loop works primarily with arrays. It
allows us to loop through each element in the array, without having to know how many elements the
array actually contains.
Its syntax for use with arrays is:
for (index in arrayName)
{
// some code
}
Example:
var myArray = new Array("Paul","Paula","Pauline");
To access each element using a conventional for loop:
var loopCounter;
for (loopCounter=0; loopCounter<3;loopCounter++)
{
document.write(myArray[loopCounter]);
}
To do exactly the same thing with the for…in loop:
var elementIndex;
for (elementIndex in myArray)
{
document.write(myArray[elementIndex]);
}
Try It Out – for…in Loop
1. <HTML>
<SCRIPT LANGUAGE = JavaScript>
var myArray = new Array("Paul","Paula","Pauline");
var loopCounter;
for (loopCounter=0; loopCounter<3;loopCounter++)
{
document.write(myArray[loopCounter]);
}
</SCRIPT>
</HMTL>
The while Loop
The while loop allows you to test a condition and keep on looping while it’s true. The for loop is
useful where you know how many times you need to loop. The while loop is more useful where you
don’t know how many times you’ll need to loop.
Syntax Form:
Condition – keep looping while this
condition evaluates to true
while (degCent !=100)
{
// some code Code looped through
}
We can see that the while loop has fewer parts to it than the for loop. The while loop consists of a
condition which, if it evaluates to true, causes the block of code inside the curly braces to execute
one, and then the condition is re-evaluated. If it’s still true, then the code is executed again and the
condition is re-evaluates again, and so on until the condition evaluates to false.
One thing to watch out for is that if the condition if false to start with, then the while loop never
executes.
Try It Out – while Loop
1. <HTML> 2. <HTML>
<SCRIPT LANGUAGE = "JavaScript"> <SCRIPT LANGUAGE = "JavaScript">
var x = 0; var x = 0;
while (x<=3) while (x<=3)
{ {
document.write(x) x++;
x++; document.write(x, "<BR>");
} }
</SCRIPT> </SCRIPT>
</HMTL> </HMTL>
3. <HTML> 4. <HTML>
<SCRIPT LANGUAGE = "JavaScript"> <SCRIPT LANGUAGE = "JavaScript">
var x = 3; var x = 0;
while (x>0) while (x<=3)
{ {
x--; x++;
document.write(x); document.write("ICC","<BR>");
} }
</SCRIPT> </SCRIPT>
</HMTL> </HMTL>
Infinite Loop
A loop that will never end. Example, if we forgot to include the x++; line leaving this line out would
mean that x will remain at zero so the condition will always be true and the loop will continue.
Example:
var x = 0;
while (x<=10)
{
alert("value x is " + x);
x++ ;
if (x = 10)
{
alert ("The last loop");
}
}
var i = 10;
while (i! = 5)
{
document.write("ICC");
}
The do…while Loop
With the while loop, we saw that the code inside the loop only executes if the condition is true; if it’s
false the code never executes, and execution instead moves to the first line after the while loop.
However, there may be circumstances when you want the code in the while loop to execute at least
once, regardless of whether or not the condition in the while statement evaluates to true. It might
even be that code inside the while loop needs to be executed before we can test the while
statement’s condition. It’s situations like this that the do…while loop is ideal for.
Try It Out – do…while Loop
1. <HTML> 2. <HTML>
<SCRIPT LANGUAGE = "JavaScript"> <SCRIPT LANGUAGE = "JavaScript">
var x = 3; var x = 0;
do do
{ {
document.write(x, "<BR>"); document.write(x);
x--; x++;
} }
while (x>3); while(x<=5);
</SCRIPT> </SCRIPT>
</HMTL> </HMTL>
3. <HTML>
<SCRIPT LANGUAGE = "JavaScript">
var x = 0;
do
{
document.write(x);
x= x + 3;
}
while (x<=5);
</SCRIPT>
</HMTL>
The break and continue Statements
We met the break statement earlier when we looked at the switch statement. Its function inside a
switch statement is to stop code execution and move execution to the next line of code after the
closing curly brace of the switch statement. However, the break statement can also be used as part of
the for and while loops when you want to exit the loop prematurely.
The continue statement is similar to break in that it stops the execution of a loop at the point it is
found, but instead of leaving the loop, it starts execution at the next iteration, starting with the for or
while statement’s condition being re-evaluated, just as if the last line of the loop’s code had been
reached.
Functions
A function is something that performs a particular task. Functions in JavaScript work a little like the
function button on a pocket calculator; they encapsulate a block of code that performs a certain task.
We have come across a number of handy built-in functions that perform a certain task, such as the
parseInt( ) and parseFloat( ) functions, which convert strings to numbers, and the isNaN( ) function,
which tells us whether a particular variable can be converted to a number. Some of these functions
return data, such as parseInt( ), which returns an integer number; other simply perform an action, but
return no data. You’ll also notice that some functions can be passed data, while others cannot. The
data that a function requires to be passed is known as its parameter(s).
Creating Your Own Functions
Creating and using your own functions is very simple. The diagram below shows a sample of a
function:
function name
function parameter
function convertToCentigrade (degFahren)
{
var degCent;
degCent = 5/9 * (degFahren – 32); code that executes
when function is called
return degCent;
}
Each function you define in JavaScript must be given a unique name for that particular page. The
name comes immediately after the function keyword. To make life easier for yourself try using
meaningful names so that when you see it being used later in your code you’ll know exactly what it
does.
The parameters for the function are given in parentheses after the function’s name. A parameter is
just an item of data that the function needs to be given to do its job. Not passing the required
parameters will result in an error. A function can have zero or more parameter, though even if has no
parameters you must still put the open and close parentheses after its name.
Example:
function myNoParamFunction( )
Functions also gives us the ability to return a value from a function to the code that called it. We use
the return statement to return a value. You don’t have to return a value if you don’t want to, but you
should always include a return statement at the end of your function, although JavaScript is a very
forgiving language and won’t have a problem if you don’t use a return statement at all. When
JavaScript comes across a return statement in a function, it treats it a bit like break statement in a for
loop – it exits the function, returning any value specified after the return keyword.
Example 1:
function writeUserWelcome(userName)
{
document.write("Welcome to my website "+userName + "<BR>");
document.write("Hope you enjoy it! ");
}
writeUserWelcome("Paul")
Example 2:
function writeUserWelcome(userName,userAge)
{
document.write("Welcome to my website "+userName + "<BR>");
document.write("Hope you enjoy it! ");
document.write("Your age is "+ userAge);
}
writeUserWelcome("Paul",31)
Try It Out – function
<HTML>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
function greet()
{
document.write("ICC ");
}
var a = prompt("Enter your name","");
document.write("Welcome to ");
greet();
document.write(a, "<BR>");
document.write("Thank you! <BR>");
greet();
</SCRIPT>
</BODY>
</HMTL>
Sample Problem
Create a program that displays your name five (5) times. Use loop function.
<HTML>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
var a;
for (a = 0; a<5; a++)
{
document.write("Nel <BR>");
}
</SCRIPT>
</BODY>
</HMTL>
Activity 2: Creating JavaScript Program
Question 1
Create a program that output all even numbers between 1 and 25.
Question 2
Write a code that display the result of the 12 times table. Its output should be the results of the
calculation.
Sample Output:
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
...
12 * 11 = 132
12 * 12 = 144