Functions Uncut



index
Disabled back button Next Section
printable version

Section 1: Introduction

The functions that were previously introduced were greatly simplified, but in practice, most functions, like most programs, have input, processing, and output.

Parameters and the return statement will be introduced after we discuss the benefits of using functions.


Modularization

The best way to develop and maintain a large program is to construct it from smaller pieces that are more manageable than the original program, i.e., divide and conquer.

Programmer-defined functions define specific tasks that may be used at many points in a program.


There are several motivations for modularizing a program into functions:


A function is invoked by a function call, which specifies the function name and provides information (as arguments) that the called function needs to do its job.

Functions allow the programmer to modularize a program.

A common analogy for this is the hierarchical form of management. The boss does not know how the worker performs its designated tasks.

hierarchy

Section 2: Returning Values from Functions

A function is capable of returning a single value to the calling program through the function name.

The return value is returned to the calling program through the function name by using the return statement, as in return kph in the final line of the function.

//------------------------------------------
// This function converts MPH to KPH. It expects the MPH value
// to be in an input field with the id txtMPH. It reads mph from the
// form and converts it to kph. The kph value is returned to the
// calling routine.
//------------------------------------------
function convertMphToKph ()
{
// declarations
const conversionFactor = 1.609344;
var kph = 0;
var mph = 0;

// input
mph = document.getElementById("txtMPH").value;

// processing
kph = mph * conversionFactor;
kph = Math.round(kph * 100) / 100;

// output
return kph;
}

The following example shows a function call embedded in an assignment statement, as seen in the line kph = convertMphToKph()....

function calcKM()
{
// declarations
var kph = 0;

// processing
kph = convertMphToKph();

// output
document.getElementById("txtKPH").value=kph;
}

When a function returns a value, the call to the function convertMphToKph() is considered to be an expression that takes on the value returned by the function.

The above function is invoked, or called, from the click event of the button labeled "Convert".

Demo

<input id="cmdCalc" type="button" value="Convert" onclick="calcKM();" />


Single Entry / Single Exit

It is good programming practice to always try to design a function with a single entry and single exit point.

Here is a sloppy example with multiple returns:

function isEven(num)
{
if ((num % 2) == 0)
{
return true;
}
else
{
return false;
}
}

Again, we're talking about good programming practice rather than functionality.

Here is a better version with a single return statement:

function isEven(num)
{
var returnValue;
if ((num % 2) == 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
return returnValue;
}

There is a much more succinct version coming up at the beginning of the next to final section.

Section 3: Writing Functions with Parameters

The calling program supplies arguments to the function.

The declarator in the function definition (or function header) specifies the names of the parameters:

Function Header

function functionName ( parameter list )

or more detailed

function functionName ( param_1, param_2, ...., param_n )

Function Call

If a function returns a value, the function call should generally be embedded in a line of code that makes use of the return value immediately, or it should appear on the right side of an assignment statement so that the return value is assigned to a variable.

A function called 'getArea' could be called with the statement

squareFtNeeded = getArea(8.5, 7.34);

The function 'lbsToKgs' could be invoked with a line like

kgs = lbsToKgs (225);

Every time the function is called (or invoked) the calling routine is suspended and the statements that make up the body of the function are immediately executed.

After a function is executed, control returns (along with the value returned, if any) to the calling statement.


In this version of the MPH to KPH converter, the function calKM() is invoked by the button click, then calcKM() reads user input from the form, calls convertMphToKph() and sends it mph as a parameter, and receives a return value that is then written to the form.

function calcKM()
{
// declarations
var mph = 0;
var kph = 0;

// input
mph = document.getElementById("txtMPH").value;

// processing
kph = convertMphToKph(mph);     // note the parameter in the function call

// output
document.getElementById("txtKPH").value=kph;
}

//------------------------------------------
// This function receives the mph value in a parameter and
// converts it to kph. The kph value is returned to the
// calling routine.
//------------------------------------------
function convertMphToKph (mphParam)
{
// declarations
const conversionFactor = 1.609344;
var kph = 0;

// processing
kph = mphParam * conversionFactor;
kph = Math.round(kph * 100) / 100;

// output
return kph;
}

Demo

Section 4: Parameter Passing

Data can be passed from the calling routine to a function.

To add to the semantic confusion, some resources refer to both arguments and parameters as different types of parameters:

Kind of Parameter Usage
Actual Parameter Appears in a function call.
  • The corresponding formal parameter will be a value parameter with primitive data types (or a reference parameter with composite data types).
Formal Parameter Appears in a function heading.
  • Receives a copy of the value stored in the corresponding actual value parameter (or access to the original argument itself with an actual formal parameter).

There should be the same number of actual parameters in a function call as there are formal parameters in the function heading.


Value Parameters

There are two ways to pass parameters to functions: call-by-value and call-by-reference.

Call-by-value:

Section 5: More on Value Parameters

Because value parameters are passed copies of their actual parameters, anything that has a value may be passed to a value parameter.


Passing Constant Literals

Constant literals, like "@" or 48, can be passed as parameters.

The following example shows a repeatString function that accepts as parameters the string to be repeated and the number of times it is to be repeated.

//------------------------------------------
// Generates a string of duplicate characters
//------------------------------------------
function repeatString(strInput, intCount)
{
var newString = "";
for (var ctr = 0; ctr < intCount; ctr++)
{
newString += strInput;
}
return newString;
}

Notice that the function expects to receive a string and an integer.

The following code segment shows a function call that uses a string literal and a numeric literal as arguments.

//------------------------------------------
// set up title string and print it in textarea
//------------------------------------------
function generateHeading()
{
var titleString = "Year Current Year Accumulated Net Book" + "\n" +
" # Depreciation Depreciation Value" + "\n" +
repeatString("-", 48) + "\n";
document.getElementById("txtTable").value=titleString;
} // end generateHeading

Passing Variables

Variables can also be passed as arguments, as seen in the following code segment.

var characterIn = "@";
var count = 24;

var separatorLine = repeatString(characterIn, count);


Recall that with a value parameter the function receives a copy of the actual parameter's value.

When value parameters are used the actual parameter cannot be directly accessed or changed.

Because the contents of value parameters are destroyed when the function returns, they cannot be used to return information to the calling code.


Graphic Demos

Graphic Demo #1 shows memory allocation when functions are called with literal argument.

Graphic Demo #2 shows memory allocation when functions are called with a variable as the argument.

Graphic Demo #3 shows that changes to value parameters in functions have no effect on the actual parameters in the function call.

Section 6: More Examples

//------------------------------------------
// Main routine called by the button click event. Calls getIntPart and
// getRealPart2 to split number on the decimal point.
// Incoming parameter: number
// Returns: nothing
//------------------------------------------
function getParts(num)
{
document.getElementById("txtIntPart").value=getIntPart(num);
document.getElementById("txtRealPart").value=getRealPart2(num);
}

//------------------------------------------
// Uses parseInt to extract the integer portion of a number.
// Incoming parameter: number
// Returns: integer portion
//------------------------------------------
function getIntPart(num)
{
var intPart;
intPart = parseInt(num);
return intPart;
}

//------------------------------------------
// Uses getIntPart to determine real portion of a number. Due to inexact
// representation of real numbers the result may be approximate.
// Incoming parameter: number
// Returns: real portion
//------------------------------------------
function getRealPart(num)
{
var realPart;
realPart = num - getIntPart(num);
return realPart;
}

//------------------------------------------
// Improved version of getRealPart. Accounts for inexact representation of
// numeric values by limiting the decimal portion to the correct number of
// digits.
// Incoming parameter: number
// Returns: real portion
//------------------------------------------
function getRealPart2(num)
{
var decimalLocation = num.indexOf(".");
var numDigits = num.length - (decimalLocation + 1);
var decimalPlaceAdjustor = Math.pow(10, numDigits);

var realPart;
realPart = num - getIntPart(num);
realPart = Math.round(realPart * decimalPlaceAdjustor ) / decimalPlaceAdjustor;
return realPart;
}

Example function call:

onclick=getParts(document.getElementById("txtNumber").value);

Demo

Section 7: Things to Avoid

If you declare a local variable with the same name as one of the parameters and do assign it a value, it "hides" the parameter.

If you declare a local variable with the same name as one of the parameters but do not assign it a value, it seems to ignore the ocal variable.

If you declare a local variable with the same name as the function the local variable is ignored.

If two functions each have local variables with the same name, neither function can access the other function's variables.

Section 8: Even More Examples

isEven Example (this is the very brief version you were promised earlier)

function isEven(num)
{
return ((num % 2) == 0)
}

The following function is the long version of the above (from section 2), which performs the same task:

function isEven(num)
{
var returnValue;
if ((num % 2) == 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
return returnValue; }

isEven Demo


isInteger Example


Most rounding functions round a number to a specified number of decimal places.

Here is a demo of the rounding function called from a form: Rounding Demo


eMail Validation Example   (structure chart)

Section 9: Resources