
Functions are the last bit of basic programming you need to know before you can understand and perform your own serious JavaScripting. All programming languages have functions. Functions, or subroutines, as they're sometimes called, are bits of JavaScript that you can call over and over without having to rewrite them every time. A Function is something that can take an input value and give an output and/or return a value in response to it. When you send a value to a Function, it's called "passing" a value. When a Function returns a value, it's called "returning" a value. Although, you have already seen examples of this, it's worthwhile to review both of these actions here in more detail a little later on. JavaScript includes several Built-in Functions as well as Methods of base Objects. You have already seen these when you used alert(), document.write(), parseInt(), or any of the other Methods and functions you’ve been working with. Let's go on to the functions in the example listed below. If you View Source, you'll see the functions sitting in the head of the HTML document. Here it is:
OK, let's go over this function. First, all functions come in this format:
Functions' naming rules are the same as those for variables. The first character has to be a letter or an underscore. The rest of the characters can be numbers or underscore. Also, you must make sure you don't name a function the same as a variable. If you do, you'll get really strange, hard to debug, results. I use internal capitalization for my function names to make sure I don't accidentally name a function and a variable the same thing. After the function name comes a list of parameters. This function has no parameters, so I'll hold off describing parameters until the examples below. Functions with parameters - passing argumentsYou can pass a value to a Function by calling the Function and including the value you want to pass within the parentheses that follow the Function's name. Such values are called arguments. It's done like this:
The quotation marks are only necessary if you're passing a value that happens to be a text string. If you're passing a number or a variable, you wouldn't use quotation marks. Functions can be set up to accept arguments that are sent to them by including a variable name in the parentheses that follow the name of the Function when it is being declared. When you do this, the Function will treat the variable throughout the rest of the Function as equal to whatever argument is passed to it. Here's an example of a Function that is set up to accept an argument.
In this Function, name takes on the value of anything that is passed to the Function. Therefore, this Function "writes" the name that was sent to it. NOTE: variables, literals, and objects can be passed as arguments when calling a function. Objects Properties & Methods are also available to function.
NOTE: name in this instance is just a placeholder. What we are saying is, wherever name exist put the passed argument here. We can use any name we want as illustrated below.
Another Example - passing multiple arguments. <SCRIPT>
5 3 7
3 7 5
5
3
7 } </SCRIPT> <FORM> Five Variations of passing "information" to a function:
Reminder: If you're passing a number or a variable, you don't use quotation marks. If a variable is passed to the function, changing the value of the parameter within the function does not change the value of the variable passed to the function. Parameters exist only for the life of the function – if you call the function, and values they held when the function last ended are retained. If you were to add the line below to printName(user) changing the value of name:
name would change, but variable user, which was sent as an argument, would not change.
The keyword this needs some explanation. this refers to this object, whatever that happens to be. It could be an entire form or just a text field or button. <INPUT TYPE="BUTTON" VALUE="Lincoln" NAME="Lincoln" onClick="Quotes(this);"> this refers to the button Object and all its Properties (VALUE="Lincoln" NAME="Lincoln") and all its Methods (in this case the button doesn't have any Methods associated with it) <FORM NAME="FormInfo"
METHOD="POST"
ACTION="JMail.asp" this refers to the Form (FormInfo) and all its Properties and Methods and all the of the Form's elements and their Properties and Methods. Wherever "this" finds itself, that is what "this" is referring to, from the opening to the closing tags whatever they happen to be. For a Form that happens to be <FORM...> ...</FORM>, and for form elements that happens to be <INPUT...>. <INPUT TYPE="BUTTON" VALUE="Lincoln" NAME="Lincoln" onClick="Quotes(this.form);"> this.form passes the Form to the function Quotes(), instead of "just" the button. <INPUT TYPE="BUTTON" VALUE="Lincoln" NAME="Lincoln" onClick="Quotes(this.name);"> this.name passes the button's Property NAME="Lincoln" to the function Quotes(). As we have seen, Functions are also capable of returning values. This is done by using the return command:
This Function asks the user to input the name of the current day and then returns that value. Now, when a Function returns a value, the Function takes on that returned value. This may be a little hard to understand, so here's an example that helps to explain:
In this example, we didn't just call a Function, we actually created a variable called dayName and set it equal to the Function. This causes the Function to be called, and it also puts the return value of that Function into the variable dayName. Also note that Functions stop executing after they execute a return command, so anything that comes after a return command will be ignored. NOTE: The return statement can be used to return any valid expression that evaluates to a single value.
the return statement will return the value of the variable cube. This function could just as easily have been written like this:
This works because the expression number * number * number evaluates to a single value. You can have more than one return statement in your function so that you can return different "things" depending upon what has happened within the function. Check out "Multiple Returns" to see how this works. The variable name exists only within the function printName() – cannot be referred to or manipulated outside the function. It comes into existence when the function is called and ceases to exist when the function ends. If the function is called again, a new instance of name is created. In addition, any variable declared using the var varName within the function will have a scope limited the function. If a variable is declared outside the body of a function, it is available throughout a script – inside all functions and elsewhere. Variables declared within a function are known as local variables. Variable declared outside functions and available throughout the script are known as global variables. If you declare a local variable inside a function that has the same name as an existing global variable, then inside the function, that variable name refers to the new local variable and not the global variable. If you change the value of the variable inside the function, it does not affect the value of the global variable. Variables can be either global or local.
An Event Handler makes 2 Function calls using Global Variables In the following example, a global and a local variable are declared.
The global variable is called globalvar1, and is declared before the function fivetimestwo() is defined. The local variable, localvar1, is able to use the value of globalvar1 and multiply it by two. The alert() method is then used to display a warning box with the text "Five times two is 10." If a second function followed fivetimestwo(), it would be able to use the globalvar1 variable, but the localvar1 variable would not be recognized. The keyword should only be used for declaring a variable so that once you declare: var globalvar1 = 5, if you want to change the value later in the script you would simply say: globalvar1 = 8. See an example that demonstrates global -vs- local variable
This ensures that all functions have been parsed before it possible for user events to invoke a function. This is especially relevant once you begin working with event handlers where incorrect placement of a function definition can mean an event can lead to a function call when the function has not been evaluated and the browser doesn’t know it exists. When this happens, it causes an error message to be displayed. Parsed refer to the process by which the JavaScript interpreter evaluates each line of script code and converts into a pseudo-compiled Byte Code (much like Java), before attempting to execute it. At this time, syntax errors and other programming mistakes that would prevent the script form running may be caught and reported to the user or programmer. The following three examples will illustrate Where You Put Your
Function Is Important: Let’s rework Using conditional operators to test input (annotated version) by creating a function that receives a question as an argument, poses the question, checks the answer, and returns an output string based on the accuracy of the user’s response. First Function & eval() (annotated version) (eval() revisited) This script seems to look more complicated, but it simply separates the work into logical blocks and moves most of the work into the function testQuestion(). eval() Method executes JavaScript code from string. Returns the value of the evaluated code, if any. It can evaluate a string to a numeric value; for instance:
Uses the conditional operator to check the user’s response. The resulting value is returned by the return command
The function testQuestion() gets called and it passes a string. testQuestion returns a result which is stored in the variable result, which then is outputted using document.write().
The last two lines could be condensed into a single line:
Recursive refers to situations in which functions call themselves.
This function relies on the fact that the factorial of a number is equal to the number multiplied by the factorial of one less than the number. Expressed mathematically, this could be written:
Which is what factorial() does. factorial() returns a value of 1 if the argument is equal to 1 or applies the formula and returns the number multiplied by the factorial of one less than the number. Note: recursive functions are powerful, but they can be dangerous if you don’t watch out for infinite recursion. Infinite recursion occurs when the function calls itself forever without stopping. In JavaScript infinite recursion isn’t likely to happen because of the way in which JavaScript handles some memory allocation. This means that deep recursions, even if they aren’t infinite, may cause the browser to crash. factorial() prevents infinite recursion because the if - else ensures that eventually the function will stop calling itself once the number passed to it is equal to one. Using recursive functions, it is possible to extend the program used in First Function & eval() so that it continues to ask the question until the users provides the correct answer as in Using a recursive function to repeat input. Notice the single change to the conditional expression:
Now instead of returning the incorrect variable for an incorrect, the returned result is the asking of the question again (by calling the testQuestion() again). NOTE: it is important to realize that this example could cause JavaScript to crash because of its memory handling problems if the user never provides the correct answer. This can be solved by adding a counter to keep track of the number of chances the user has to provide a correct answer:
If the user’s response is correct ( response == answer) it returns the value correct. Otherwise, if there are chances left (chances > 1) ask the question again and return the result. If there are no chances left and the answer is incorrect, return the value of the variable incorrect. |