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.
- Input is performed through the use of parameters.
- Processing is performed as in previous code.
- Output is performed through the use of a return statement.
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.
- This is known as modularization.
Programmer-defined functions define specific tasks that may be used at many points in a program.
- The statements that make up the function are written only once and these statements are not visible to other functions.
There are several motivations for modularizing a program into functions:
- The divide-and-conquer approach makes program development more manageable.
-
Modularization allows software reusability
using existing functions as building blocks to create new programs.
- With good function naming and definition, programs can be created from standardized functions, rather than being built by writing customized code.
- Modularization allows a program to be divided into modules that can be developed concurrently by multiple programmers.
-
Modular design also makes it possible to avoid repeating code in a program.
- Packaging code as a function allows that code to be executed from several locations in a program simply by calling the function.
- Programmers can create functions to meet the unique requirements of the problems they are solving.
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.
- A boss (the caller) asks a worker (the function) to perform a task and return (i.e., report back) the results when the task is done.
- The worker may call other workers to help; the boss will be unaware of this.

Section 2: Returning Values from Functions
A function is capable of returning a single value to the calling program through the function name.
- However, a function may or may not return a value to the calling routine.
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.
- That value is assigned, in this case, to the variable kph.
- (Remember that in an assignment statement, the right-hand side is evaluated and its value is stored in the left-hand side.)
The above function is invoked, or called, from the click event of the button labeled "Convert".
<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.
- I can stop my vehicle by driving into a tree, but that is not good driving practice.
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 variables used within the function to hold the argument values are called parameters.
The declarator in the function definition (or function header) specifies the names of the parameters:
- These parameter names are used in the function as if they were normal variables.
- When the function is called, its parameters are automatically initialized to the values passed by the calling program.
- The types in the declaration and the definition do not have to be identical, however logic dictates that they should be.
- There should be the same number of arguments in the function call as there are parameters in the function declaration.
- There is more on parameter passing in the next section.
Function Header
function functionName ( parameter list )
or more detailed
function functionName ( param_1, param_2, ...., param_n )
- All function definitions contain parentheses, which may be empty or may contain one or more parameter variable declarations (called a parameter list).
- Parameter variables receive their values from the function call and are used in the function body.
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.
- Program execution then continues with the next statement after the call.
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;
}
Section 4: Parameter Passing
Data can be passed from the calling routine to a function.
- The calling program supplies arguments to the function.
- The variables used within the function to hold the argument values are called parameters.
-
Note that while we sometimes use the two terms interchangeably, they are
subtly different.
- Here is a discussion about Parameters & Arguments in JavaScript.
- One major difference is that arguments can be variables (like mph) or actual literals (values like 55), while parameters are "containers" similar to variables.
- That said, the two terms are generally used interchangeably.
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.
|
Formal Parameter | Appears in a function heading.
|
There should be the same number of actual parameters in a function call as there are formal parameters in the function heading.
- JavaScript actually allows you to violate this (but don't).
- Read more in JavaScript function that accepts any number of arguments.
Value Parameters
There are two ways to pass parameters to functions: call-by-value and call-by-reference.
-
With call-by-value the function is given a copy of the parameter to work with.
- In JavaScript, when passing in a primitive type variable like a string or a number, the variable is passed in by value.
-
With call-by-reference, the function has access to the original variable in the
calling routine and can alter that value.
- Call-by-reference parameters will be discussed in the lecture on arrays.
Call-by-value:
- Call-by-value is the default argument passing approach for primitive data types.
-
The function creates new variables to hold the values of the arguments.
- The function gives these new variables the names of the parameters specified in the declarator and initializes these parameters to the values passed.
- They can then be accessed like other variables by statements in the function body.
- In other words, a function call passes a copy of the argument's value to the called function, and that copy can be manipulated without affecting the original value in the calling routine.
-
This makes it possible to modify the values in the function without affecting the
original variables.
- This offers insurance that the function cannot harm the original variable by using a copy of the original variable.
- This also ensures that the only way that a function can return a value is through the return statement.
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.
- This includes constants, variables, and even expressions.
- Expressions are evaluated and a copy of the result is sent to the corresponding 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.
- When a function returns, the contents of any value parameters are destroyed, along with the contents of the local variables.
- The difference between value parameters and local variables is that the values of local variables are undefined when a function starts to execute, whereas value parameters are automatically initialized to the values of the corresponding actual parameters.
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);
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;
}
Most rounding functions round a number to a specified number of decimal places.
- Math.round provided by JavaScript, however, does not allow you to specify decimal places but rather rounds to the nearest whole number.
- In previous assignments we rounded to one decimal position by multiplying by 10, rounding, and then dividing by 10. We can get two decimal places by replacing 10 with 100.
- If you need a round function that will round a number to a specified number of decimal places you have to write your own.
-
The following function will do just that:
function newRound(num, positions)
{
var decimalPlaces;
var roundedValue;
decimalPlaces = Math.pow(10,positions);
roundedValue = Math.round(num * decimalPlaces) / decimalPlaces;
return roundedValue;
}
-
You can call the function in a number of ways. Here is a sample call:
alert("The number " + testNum + " rounded to " + places + " places is " + newRound(testNum, places) + ".");
In this case the alert would display "The number 34.689223 rounded to 2 places is 34.69."
Assume the following declarations are used
var testNum = 34.689223;
var places = 2;
Here is a demo of the rounding function called from a form: Rounding Demo