CS114 Using Selection/Iteration Constructs and Functions
1.0 Selection Constructs
6-1
Using Selection/Iteration Constructs and Functions CS114
6-2
CS114 Using Selection/Iteration Constructs and Functions
2.0 Iteration Constructs
6-3
Using Selection/Iteration Constructs and Functions CS114
3.0 Functions in JavaScript
A collection of program statements maybe grouped into a function to perform a
particular task.
A function begins with the keyword function followed by the name assigned to the
function and a pair of parentheses. Usually some information need to be passed to the
function as parameters.
4.0 Example
function area_of_square(length)
{
var area=length*length;
return area;
}
5.0 Calling functions
A function does not execute automatically.
To execute a function, you must call it from elsewhere in the program.
To call the function, you must create a statement that includes the function name,
followed by a parenthesis containing any variables or values to be assigned to the
function’s arguments.
Using the previous example, the function call would be area_of_square(10) .
6-4
CS114 Using Selection/Iteration Constructs and Functions
6.0 Exercise 1
Write a function in JavaScript that calculates the total and the average of three integer
values. The program should display the total and the average in an alert window.
Solution
6-5
Using Selection/Iteration Constructs and Functions CS114
7.0 Exercise 2
Write a simple program that calculates the tax to be paid by the customer. The program
should read in the total purchase value and add in the tax rate of 3.0%. The tax
amount and the total purchase value with tax should be displayed.
Solution
6-6
CS114 Using Selection/Iteration Constructs and Functions
8.0 Exercise 3
Write a JavaScript function that displays the capital cities in South East Asia when the
user keys in the country. The program should use an if else construct.
Solution
6-7
Using Selection/Iteration Constructs and Functions CS114
9.0 Exercise 4
Write a JavaScript function that displays the capital cities in South East Asia when the
user keys in the country. The program should use a switch-case construct
Solution
6-8