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 Scripting Master!");</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:
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: