Function Review

In a web pages, JavaScript code written in <script> tags executes automatically when the page loads it. For example, a page that has some text, JavaScript alert code and two images (in that order), will load the text, pop up the alert, and will only show the images AFTER the alert has been dismissed. In order to keep the alert from happening until we want it to, we need to put the JavaScript code in a function (also known as a method). A function is defined as a type of procedure or routine. The idea is that we encapsulate several lines of code that may need to be called often into a function so that they can be called with a single line. In JavaScript, a function is written using the following code: function functionName() { //lines of code go here } Where "functionName" is any valid identifier name. Like with variables, the name should be indicative of what the function does. If the function is designed to calculate a persons pay, we may call it calculatePay. Regardless of the name, it should always be followed by a set of parenthesis () and curly braces {}. All of the code for the method goes in the curly braces. function alertHello(){ window.alert("Hello"); } Any JavaScript code can be placed in a function. We can write functions that would draw shapes on a canvas, ask users for information and perform calculations, etc. The main difference at this point, is that the code in a function WILL NOT EXECUTE until we call it, whereas all other JavaScript on the page will execute as it is loaded.

Information can be sent into a function using parameters. Parameters are a comma separated list of variables inside the parenthesis. The parameter variables must be given a value prior to the function being called. In the example below, the variables value1, value2 and value3 are initialized in the main and then sent into the function. In the function, they are referred to by their parameter names, param1, param2, and param3, where param1=value1, param2=value2 and param3=value3. function function1(param1, param2, param3){ window.alert(param1+param2+param3); } ///main javascript code var value1=5; var value2=6; var value3=7; function1(value1, value2, value3);

Function Returns

We have now seen how to send informtion into a function, but to get information back from a function we use a return statement. A function can only return one value, so it is important to create functions that complete a single task. It is also important to store the value that is returned in a variable. See the example below. function mult(val1, val2){ var product=val1*val2; return product; } //main code var num1=parseInt(window.prompt("Enter a number")); var num2=parseInt(window.prompt("Enter a number")); var result=mult(num1, num2); //result now stores the value of the product variable from the method window.alert(result);