Creating JavaScript functions
If you have to write a large program, you may consider using functions. Functions allows you to easily reuse your code. A function is a series of commands that either calculates a value or performs an action. A function consists of function name, which identifies it, parameters, the values passed to the function, and the set of commands that run when the function is called. To use a function, you call the function. When you call the function, you pass (send) the values used by the function. Note that not all functions require you to pass values; thus parameters are optional. Functions can also return a value, the result of the calculation or the output of the function sent back from the function.
The general syntax of a JavaScript function is:
function functionName (parameters) {
JavaScript commands
}
where
functionName = name of the function
parameters = values sent to the functions
JavaScript commands = commands that run when the function is called or used
A function starts with the keyword function. All the commands that belong to a function must be placed inside the curly braces { }. The set of commands placed inside the curly braces is referred to as a commands block. The commands block combined with the function name is referred to as a function definition. In other words, a function definition tells you what the function is and what it does.
Before you start creating your own JavaScript functions, keep in mind that JavaScript function name must begin with a letter or underscore (_). The function name cannot contain any spaces. Also, like variables, function names are case-sensitive. Thus calculateSalary and CalculateSALARY are considered different function names. For the function parameters, there is no limit in the number of function parameters a function contains. The function parameters must be placed inside the parentheses, following the function name, and each parameter must be separated by a comma. Pay attentions to these rules in the JavaScript functions examples shown as below:
Performing an action with a function
To create a function, first decide what exactly you want the function to do. For now, we will start with a simple JavaScript function that will print a message to the screen. Remember the idea behind using functions is to reuse and organize your code. That should start to make sense as follow examples shown on this page.
Suppose we have the following function definition:
function DisplayMessage () {
document.write ("Learn JavaScript from the Script Buzz!");
}
The name of this function is DisplayMessage. Anytime we want to use this function, we will use the function name we listed between the keyword function and parentheses. When we say we want to use or call a function, we are saying we want the function to run the code inside function. Recall the code inside the curly braces is called command block. In the DisplayMessage function, our command block only consists of a statement that will print a message using the document.write method.
Note that our function takes no parameters. Recall parameters are listed inside the parenthesis. To call the DisplayMessage function, we will simply write
DisplayMessage ()
Now, let’s use this example to show you how to use a function in JavaScript:
<script language="javascript">
function DisplayMessage () {
document.write ("Learn JavaScript from the Script Buzz!");
}
document.write ("Calling the function....<br>");
DisplayMessage ();
document.write ("<br>..Done!");
</script>
The execution of this script will begin on line 5 and that prints the “Calling the function…..” Remember that a function is executed only when you call the function. We call the function on line 6. When the function is called, the code inside the function will be executed. So after line 6, line 2 will be executed that states the name of the function and indicates that it takes no parameters because of the empty parentheses. Next, line 3 will be executed to print the “Learn JavaScript from the Script Buzz!” Line 4 ends our function. Finally, line 7 will be executed to print “..Done!” The following shows the output of the above JavaScript code:
Calling the function….
Learn JavaScript from the Script Buzz!
..Done!
As you may have noticed, when we use functions we are changing the order in which the statements in our scripts are executed. In other words, your statements may not run in the order they are listed in your program. This type of control structure is referred to as non-linear (non-sequential) execution. In our JavaScript code above, lines 2, 3, and 4 were executed after line 6.
With this one example, don’t feel that functions make you write extra code. Remember the idea behind using functions is to reuse code. For instance, let’s say we wanted to print a long welcome message in 5 different places of our program. For that example, we would define a function that contains our welcome message. Anytime we need to print that message we just simply call the function. You don’t have to write 5 different document.write () methods for the welcome message at five different locations in your program!
Passing parameters to functions
In the previous section, you saw how to define a function and use a function. In this section, you will learn how to pass parameters (or values) to a function. Let’s continue with the example we used in the previous section. We will change our function definition and the other JavaScript code as follows:
<script language="javascript">
function DisplayMessage (message) {
document.write (message + "<br>");
}
DisplayMessage ("Hello,");
DisplayMessage ("Learn JavaScript, HTML, ASP and more from the Script Buzz!");
</script>
This function takes in one parameter called message, see line 2. Remember parameters are listed inside the parentheses. On line 3, we print the value of message. On line 5 and 6, we call the function DisplayMessage () and pass different values each time. The following shows the output of the above code:
Hello,
Learn JavaScript, HTML, ASP and more from the Script Buzz!
As another example, let’s write a function that will calculate a person’s salary; we will ignore taxes or any other deductions. For this function, we will pass three parameters: employeeName, hoursWorked, and payRatePerHour. The following shows the JavaScript code:
<script language="javascript">
calculateSalary (employeeName, hoursWorked, payRatePerHour) {
var totalSalary;
totalSalary = hoursWorked * payRatePerHour;
document.write (employeeName + ", your salary for this week is: $" + totalSalary + "<br>");
}
calculateSalary ("Steve", 25, 30);
calculateSalary ("John", 40, 40);
</script>
Note in our function definition (line 2) and when we call the function (lines 7 and 8) that each parameter is separated with a comma. Also, when you pass values to a function, make sure you send the values in the order the function expects the values. For this function, the first parameter expects a string, the second parameter expects the number of hours a particular person has worked, and the third parameter expects the pay rate for an individual. The following shows the output of this example:
Steve, your salary for this week is: $750
John, your salary for this week is: $1600
Returning a value from a function
To return a value from a function, use the return command along with a variable or value at the end of the function’s command block. Consider the following function definition:
function isEven (num) {
if (num % 2 == 0) {
return num;
}
}
This function determines if a number is even. This function takes one parameter, num. On line 4, we return the value of num. Note line 4 is only executed if the Boolean expression on line 3 is true. Note that our Boolean expression uses the modulus operator. Let’s find even numbers between 1 and 20 by using the function definition we show above.
In the following code,
<script language="javascript">
function isEven (num) {
if (num % 2 == 0) {
return num;
}
}
function printMessage (num) {
if (num > 1) {
document.write (num + " ");
}
}
var evenNum;
document.write ("Even numbers: ");
for (i = 1; i <= 20; i++)
{
evenNum = isEven (i);
printMessage (evenNum);
}
</script>
we are using two functions. We call the isEven () function on line 16 inside a for loop. Our for loop is on lines 14 through 18. The for loop executes 20 times and calls the isEven () function and the printMessage () function 20 times. The first time the isEven function is called with the parameter value 1. The function returns nothing because 1 % 2 does not equal 0, so the printMessage () function will print nothing. However, when the second time the for loop is run, the value 2 is passed to the isEven () function. This is a even number because 2 % 2 is 0 so the function will return 2. In this case, the printMessage () function will print the number 2. The following shows the output of the JavaScript code:
Even numbers: 2 4 6 8 10 12 14 16 18 20