JSFunctions

Definition of a Function
A function is a block of code that will be executed when called. It is a subprogram (subroutine) designed to perform a specific task and to return a value. Once a function executes, control is transferred back to the calling function or the Compiler (Operating System).

It is a technique used to isolate a group of instructional code (modules) so that other parts of the application can depend on it to provide them with a reliable result (in a technique referred to as modular approach of programming). There are two main categories of functions you will be using in JavaScript: those that have already been created for you(built in functions) and those you create in your code (user defined functions).

User defined functions
Function Definition:

To create a function, type the function keyword followed by a name for the function, followed by an opening, then a closing, parentheses, followed by an opening curly bracket “{“ and ending with a closing curly bracket “}”. Here is the syntax for creating a function:

function name(optional Parameters){}

The function keyword is required. It lets the browser know that you are creating a function. The name of the function:

Must start with a letter or an underscore Can contain letters, digits, and underscores in any combination Cannot contain space Cannot contain special characters

JavaScript Function Syntax

A function is written as a code block (inside curly { } braces), preceded by the function keyword: Example one: Function without parameters function functionname {   some code to be executed }

Example 2: Function with parameters function functionname(recBase, recHeight) {   some code to be executed }

The code inside the function will be executed when "someone" calls the function.

The function can be called directly when an event occurs (like when a user clicks a button), and it can be called from "anywhere" by JavaScript code. lamp 	JavaScript is case sensitive. The function keyword must be written in lowercase letters, and the function must be called with the same capitals as used in the function name.

Calling a Function with Arguments

When you call a function, you can pass along some values to it, these values are called arguments or parameters.

These arguments can be used inside the function.

You can send as many arguments as you like, separated by commas myFunction(argument1,argument2) Declare the argument, as variables, when you declare the function: function myFunction(var1,var2) {  some code }

The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc.

Example: Try it   function myFunction(name,job) {     alert("Welcome " + name + ", the " + job); }

JavaScript Function Syntax

A function is written as a code block (inside curly { } braces), preceded by the function keyword: function functionname {  some code to be executed }

The code inside the function will be executed when "someone" calls the function.

The function can be called directly when an event occurs (like when a user clicks a button), and it can be called from "anywhere" by JavaScript code. lamp 	JavaScript is case sensitive. The function keyword must be written in lowercase letters, and the function must be called with the same capitals as used in the function name.

Calling a Function with Arguments

When you call a function, you can pass along some values to it, these values are called arguments or parameters.

These arguments can be used inside the function.

You can send as many arguments as you like, separated by commas myFunction(argument1,argument2)

Declare the argument, as variables, when you declare the function: function myFunction(var1,var2) {    some code }

The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc. Example: Try it    function myFunction(name,job) {       alert("Welcome " + name + ", the " + job); }

When naming your functions, be explicit, give names that can identify what mission the function is carrying. For example, if a function displays something, you can call it display. If the name of the function is a combination, you can type an underscore between them, like this: show_window. Alternatively, you can start the first letter of the first word in lowercase and the first letter of each of the other parts in uppercase, like this: showWindow

The parentheses are required, they set apart a function from the other items of your script or web page. We will find out that they can also be used for other things.

The assignment carried by the function is delimited by the opening and the closing curly brackets {}. Everything between the bracket is part of the function. The section between the brackets is called the body of the function. A function can consist of a simple operation, an expression, or a series of more complex code. For example, you can use the document.write method that we have called previously to display a string. If the assignment carried by the function is made of a single and simple line, you can write the whole function in one line. Here is an example:

 function showAddress{document.write("12404 Lockwood Drive #D4");} 

Code written on a single line with the function name is difficult to read. Besides, most of your functions will consist of many lines of code. Therefore, it is better not only to separate the function name from its code but also to indent it, which makes it easier to read. The above function could (and should) be written as follows:

 function showAddress {     document.write("12404 Lockwood Drive #D4"); } 

From our previous knowledge of HTML, we have learned so far that the browser is mainly used to give simple instructions to the browser. While the body of the HTML file is used to display items, the code we write is dealt with behind the scenes. For this reason, it can be included in the head section of an HTML file. Here is an example:

JavaScript Tutorial  function showAddress {       document.write("12404 Lockwood Drive #D4"); }    Graphical User Interface Objects

A function can also have its code in the same section where it is needed as many of the functions on this site will be implemented.

Practical Learning: Defining Functions

To define a function, change the file as follows:

Henley's Department Store  function welcomeMessage {     document.write("Welcome to Henley's Department Store!"); }    Henley's Department Store Customers Order Processing

Save the file

Function Calling

Using a function is referred to as calling the function. Because a JavaScript function is not part of HTML, there are some rules you should follow to call it. So far, we have been calling a function called write which is a member of the document object. As you recall, we had to start the calling of the function with the tag. In the same way, if a function is able to carry a complete assignment, you can call it between the and tags.

To call the simplest JavaScript function such as the one above, type the name of the function followed by its parentheses. Here is an example:

 function showAddress {   document.write("12404 Lockwood Drive #D4"); }   showAddress; 

Practical Learning: Calling Functions

Call the above function as follows: Henley's Department Store  function welcomeMessage {     document.write("Welcome to Henley's Department Store!"); }    Henley's Department Store Customers Order Processing  welcomeMessage; </Script> JavaScript Tutorial <h2 font face="Georgia, Garamond, Times New Roman" color="#FF0000"> Credit Application <font face="Verdana, Tahoma, Arial" size="3"> <form name="CreditApplication">

Functions and Local Variables
When it receives assignments, a function is supposed to handle a specific task to produce a result. If a function is not given some items it needs, it can provide its own accessories. This means that you can declare some variables that the function needs, manipulate those variables as you wish and hand the expected result to other sections of the program or file that need it.

You declare a variable in the body of a function the same way you declare a variable in the scripts we have used so far. A variable declared in the body of a function is referred to as a local variable. Here is an example:

 function showAddress { var customerAddress; } </Script>

After declaring such a variable, you can initialize it and hand it to another function such as document.write. Here is an example:

 function showAddress { var custAddress; custAddress = "12404 Lockwood Drive #D4"; document.write(custAddress); } </Script>  showAddress; </Script>

A locally declared variable can also be involved in any operation as you see fit. In the following example, local variables are declared to hold different values for the calculation of a net price. Other variables are declared to hold sentences to display on the web page. The sentences are then passed to the document.write method to display them:

 function calculateTheDiscount { var itemPrice = 120.55; var discountRate = 0.20; // = 20% var discountAmount = itemPrice * discountRate; var netPrice = itemPrice - discountAmount; var sentence1 = "Item Price: $" + itemPrice + " "; var sentence2 = "Discount: $" + discountAmount + " "; var sentence3 = "Net Price: $" + netPrice + " ";

document.write(sentence1); document.write(sentence2); document.write(sentence3); } </Script>  calculateTheDiscount; </Script>

Using a Function's Local Variables
To declare and use some local variables in a function, change the file as follows: JavaScript Tutorial

 function getFullName {     var firstName, lastName, fullName; firstName = document.CreditApplication.txtFirstName.value; lastName = document.CreditApplication.txtLastName.value;

fullName = firstName + " " + lastName; document.CreditApplication.txtFullName.value = fullName; }   </Script>

<h2 font face="Georgia, Garamond, Times New Roman" color="#FF0000"> Credit Application

<font face="Verdana, Tahoma, Arial" size="3"> <form name="CreditApplication">

Functions and External Values
Passing an Argument

When asking a function to perform an assignment, a function may need to be given the necessary value to perform its job. For example, if a function is supposed to calculate the area of a square, the function may need at least the measurement of the side to proceed. Another function that needs to calculate the price of an item after applying a discount rate would need the item’s price and the discount rate; such a function would produce the net price (price after discount).

An item or value that a function needs is called an argument. It can also be called a parameter. An argument for a function is provided between the parentheses for the function that will need it. Providing an argument to a function is referred to as passing the argument.

To pass an argument to a function, when implementing the function, type a variable name that represents the argument. Here is an example:

function circleArea(radius);

In the body of the function, use the argument any way you see fit. For example, its value can be involved in a calculation. Here is an example of a function that is passed an argument. The function calculates the area of a circle using the radius that is supplied:

 function circleArea(radius) { var area; area = radius * radius * 3.14159; } </Script>

To call a function that takes an argument, you must supply the argument. If you know the value of the argument, you can provide it:

 function circleArea(radius) { var area; area = radius * radius * 3.14159; document.write("The area of the circle is ", area); } </Script>

 circleArea(20.75) </Script>

You can also provide the argument using the name of the variable that holds the necessary value. The variable that is passed and the argument used by the function don’t need to have the same name but they must be of the same data type. For example, if a function is using a numeric value to perform a calculation, make sure that the variable you are providing is holding a numeric value. Here is an example of passing an argument to a function using the name of a variable:

 function circleArea(radius) { var area; area = radius * radius * 3.14159; document.write("The area of the circle is ", area); } </Script>

 var measure = 45.25; circleArea(measure ); </Script>

A function can also take more than one argument. In this case, provide a name for each argument between the parentheses of the function. The arguments must be separated by a comma. Here is an example:

function rectangleArea(length, height);

In the body of the function, use the variables in any necessary way. Here is an example:

 function rectangleArea(length, height) { var area; area = length * height * 3.14159; document.write("The area of the rectangle is ", area); } </Script>

 var L, H; L = 52.05; H = 46.55; rectangleArea(L, H); </Script>

The arguments of a function don’t have to be of the same type. One of the arguments could be a natural number (integer) while another argument could be a string; yet another argument of the same function could be a decimal number or a character. If you implement a function that takes different types of arguments, when calling the function and supplying the arguments, provide the arguments following the order of the types of arguments supplied. Here is an example of a function that takes different types of arguments:

 function rectangleArea(length, height, shape) { var area; area = length * height * 3.14159; document.write("The area of the ", Shape, " is ", area); } </Script>

 var L, H, S; L = 52.05; H = 46.55; S = "rectangle"; rectangleArea(L, H, S); </Script>

Returning a Value
When a function has performed an assignment, it may provide a value that other functions would need, for any reason you judge necessary. When a function produces a value an makes it available to other functions, such a function is said to return a value.

To define a function that returns a value, just before the closing curly bracket, type the return keyword followed by the value that the function returns. The value should be a valid and expected type. Because JavaScript is not a type-checking language, meaning it hardly checks anything you are doing, it is your responsibility to make sure that your function returns the right value.

Here is a function that returns a value:

function rectangleArea(length, height) { var area; area = length * height * 3.14159; return area; }

Even if a function returns a value, it can still be called like any other function. If a function returns a value, its name can be assigned to a variable to give a value to, or change the value of, the variable. Here is an example:

<Script Language="JavaScript"> function rectangleArea(length, height) { var area; area = length * height * 3.14159; return area; } function displayArea { var l, h, rectArea; l = 52.05; h = 46.55; rectArea = rectangleArea(l, h); document.write("The area of the is ", rectArea); } </Script>

<Script Language="JavaScript"> displayArea; </Script> Bold text