COM271, Week 8
JavaScript Functions
Defining and Invoking Functions. To define a function, use the function statement, which is the function keyword followed by the name of the function, an optional comma-separated list of argument names in parentheses (this may be an empty list), and a body of statements—a block of code surrounded by curly brackets { } . Functions may or may not contain a return statement, which stops execution of code and returns the value of the functions expression (if any) to the calling code. Once defined, a function may be invoked with its name, followed by ( ), containing any comma-separated arguments.
Example:
function add(num1,num2)
{
var sum;
sum=parseInt(num1)+parseInt(num2);
document.getElementById('sum').value=sum; }
Here is a simple form to call this function to add two numbers:
Here is the HTML and Javascript in the form:
<form onsubmit="return add(document.getElementById('num1').value, document.getElementById('num2').value) ">
(note that we are passing TWO values as parameters in the add() function.)
Number 1: <input type="text" id='num1' size="5"><br />
Number 2: <input type="text" id='num2' size="5"><br />
Sum is: <input style="margin-left:15px;" type="text" id="sum" size="7"><br />
<input style="margin-left:50px;" type="submit" value="add"></form>
How does this work? Within the html form element, the onsubmit event handler calls the function add, passing it two values: the value associated with the two elements identified as "num1" and "num2." These are form values, and as passed, they are strings. Within the function add, the two strings are converted to integers by the built-in javascript function parseInt (). The two integers are added and stored in the variable sum. Sum is then assigned as the value of the element identified as "sum," which immediately displays the numerical sum of the two values.
Passing data. Often, functions are passed values which are used within the function's code, affecting the value returned. For example, we may pass a value that is multiplied by itself to return the square of the value. These values are called arguments or parameters. The type of variable passed will be assumed within the function itself. Passing a string where a number is called for, for example, may produce an unexpected result.
Primitive data (numbers, strings) are passed by value, meaning that the value passed into a function is copied into a variable used within the function, leaving the original value unchanged. If a value x ( = 4 ) is passed into a function which uses "x" as an argument, and "x" is assigned the value 10 within the function, the value of x outside of the function remains 4.
Return The return statement indicates that a function should stop processing its code and most likely also return a value. If there are conditional branches within the function, there may be multiple return statements
Scope—Global or Local? Variables are either global or local. Global means that a variable is visible and usable anywhere in the document. Local means that a variable is visible or usable only within the block of code in which it is defined (usually, a function). Another way of saying this is that the scope of the body of a function is local. Basically, if a variable is declared (e.g., var x = ...) in the main body of a program (here, the html page, outside of any JavaScript functions), it is global. If it defined within a function, it is local. Re-declaring a global variable within a function "masks-out" the global variable, meaning that any changes that occur within the function do not affect the variable outside of the function.
Note that functions may be nested in JavaScript. That is, functions may themselves contain functions. This is a practice that is useful in the development of larger, more complex, sections of code. The practice of modularizing code is generally recommended; It has not proliferated as a practice for JavaScript, however. Remember that JavaScript is downloaded and run client-side. Resulting scripts tend to be limited, to minimize download time.
Good Practice in Using Functions: The following are good practices, recommended as a means to develop easy-maintenance code:
- Define all functions for a script first
- Name functions well (suggest using a prefix "fun" on function names), to avoid confusion with variables
- Use linked external files
- Use Return statements
- Modularize: Write stand-alone functions that use data passed by reference
- Check arguments carefully, for number and type
- Comment functions, at least through the end of the development phase