Lesson # 4 - Functions

# 4 Functions

# 4 Review Questions # 4 Assignment

In Lesson #3 you saw the Body Mass Index Calculator. It used a function to create a block of code that was called into action with just a single call from the body of the web page. In programming, a function is used to perform a set of related statements as if they were just one statement. In this lesson you will learn more about the concept of a function and how they are used to create more powerful programs.

 

A Way of Thinking About Problems 

Suppose you have to wash the car. Hooboy there are a lot of details when you think about it.

The point of the list is to break down a rather complex chore into some smaller chores. If you look at each sub-chore, none of them are really that complicated, but by putting them into the right order, we can accomplish a much larger task. Not only that, but if you get someone else to help, you could divide up the chores and share the workload. What a concept!

The same thing is true about computer solutions, even though you would have a hard time getting your computer to help you wash the car! By thinking about a large, messy problem in term of smaller chunks that belong together logically, you can create some pieces of the solution. Then when you put all the pieces together in the right order, you have something that is awesome! Sometimes, the sub-tasks need to be broken down again, until each little task is quite do-able. Solving the problem then could look like this diagram.

This process is called top-down design, because we start with the big problems at the top, then break it down into medium sized problems, then break those down into progressively smaller problems, until finally we reach a level where each problem is fairly easy to do. Then we assemble the pieces the form a complete solution to the problem at hand. Try this method next time you have to do something complex, such as a research paper, or cleaning your room.

How to Code a JavaScript Function

We start in the <HEAD> section - and use the keyword function. Here is a very simple example.

function showMsg( ) {

    document.write("This is a dumb function.");

} // end function showMsg

This function won't do anything exciting, but it shows how to set one up. It won't execute until it is called, even though it is located in the <HEAD> section. It must be called from within the <BODY> section with a JavaScript statement such as this one.

<SCRIPT >

    alert("Here comes a dumb function demonstration.");

    showMsg(); // this line calls the function called showMsg() to execute

</SCRIPT>

 

Sending Values to a Function

Most functions are more useful if they can accept some information from the calling program or from the web page and do something with it. As an example, just look at the alert() method in the example above. In the parentheses that follow the word alert, we have a string of text. That text is used when the alert() box pops up on the screen. That text is called the argument of the function. It is used by the function's statements for some purpose. In the Body Mass Index calculator, the information passed in was an entire form. We can write functions that require multiple arguments to be sent. In the function code itself, these are called parameters. The essential thing is that we have an exact match between the number and data types of the arguments in the function call, and the parameters in the function definition. For example, a function that calculates the area of a rectangle would need to accept two numbers as floats before it would know how to calculate the area. So the call to the function would have to have two arguments of type float, or an error message would occur.

Suppose now we wanted to write a function call that would ask the user to enter their name and then display a personal greeting. This is on Assignment 4 so you may want to look back here to do the assignment. We can use a text box's value to get the user's name, then call a function that accepts the name and greets your visitor. First let's write the function definition. This code is placed in the <Head> section.

function greetUser(userName ) {

    alert("Welcome to my web site " + userName );

} // end function showMsg

Next, in the <BODY> we need to create an input box that will get the name, and call the function named 'greetUser()'.

Please sign in:

<INPUT TYPE="text" VALUE = "Enter your name" onBlur="greetUser(this.value)">

    

Returning Values from a Function

Sometimes we want to have the function send some information back to the web page. The Body Mass Index program did that for us by assigning the results of three different calculations into the value properties of three text boxes to have them displayed on the web page. That is one way , but we can also use the return keyword to send a value back to the calling program. One thing to remember is that a value being returned must have some place to be stored in the calling program. So the calling program needs to have a variable to hold that information that is coming back from the function. Here is a sample of a function that does not accept any parameters, but returns a number as an integer value back to the calling program. In this case, let's suppose we want to be able to ask for a serial number for some product and have the function send it back to us. In the <HEAD> section, place the function definition:

function getSerial( ) {

   var serialNum = 12345; //serial number is an integer data type

   return serialNum;

} // end function getSerial()

Place this code in the <BODY> section.

Click here to view the serial number of your new product:

<INPUT TYPE="button" value = "Get Your Serial Number" onClick="var mySerialNum = getSerial()">

This is also one of your exercises in Assignment 4, so you will get to write and test this function. Good luck, and don't give up!

Scope of Variables

It is time to make a distinction between variables that are defined inside of a function, and those that are defined within the <SCRIPT> tags, but outside of any function's curly braces {}. What we are talking about is the variable's scope.

If a variable is declared inside of a function, then it is local to that function, meaning that outside of the function it has no visibility. Other functions cannot see it, use it, or access its contents. The only way to share local information is to pass it to the function as an argument.

By contrast, if a variable is declared outside of any function, its scope is global. That means that any function in the document that is currently in the browser window can access it to either store information or retrieve information. This is considered risky to most serious programmers, because sometimes a function will make erroneous changes to a global variable. Local scope allows you to reuse any variable names you want to, since functions cannot see or change each other's local variables. Global means less need to pass parameters, but more chances for your programs to have errors. In other programming languages, global variables are considered a big no-no because they allow sloppy coding to create errors.

Return to Top of Page | Back to Main Menu