The values you pass to functions are called arguments. When you pass data in arguments to a function, the code in the function has access to those values. When you create a function, you specify which arguments are to be passed to the function in an argument list. Here's an example. In this case, I'll create a function named adder that will add two values and return their sum. Here's how I start creating adder : function adder() { . . . } This time, we're going to pass arguments to the function. So, we list the arguments that we'll pass by giving them names in the argument list, which is enclosed in the parentheses following the function name . Here, I'll call the two arguments passed to addervalue1 and value2 : function adder(value1, value2) { . . . }
Now you're free to refer to the passed values by the names you've given them in the argument list. To return the sum of value1 and value2 , all I have to do is to add those values and use the return statement, like this: function adder(value1, value2) { return(value1 + value2) } To make use of this function, you pass values to it in parentheses like this, where I'm finding the sum of the values 47 and 99 : Listing ch06_11.html<HTML> <HEAD> <TITLE> Passing Arguments to Functions in JavaScript </TITLE> </HEAD> <BODY> <CENTER> <H1> Passing Arguments to Functions in JavaScript </H1> </CENTER> <SCRIPT LANGUAGE = "JavaScript"> document.writeln("47 + 99 = " + adder(47, 99)) function adder(value1, value2) { return(value1 + value2) } </SCRIPT> </BODY> </HTML> That's all it takes; now we're passing arguments to the adder function. You can see the results in Figure 6-11. As you see there, everything is working perfectly : The sum of 47 and 99 is displayed as it should be. (You might also note that even though the value returned from the adder function is a number, JavaScript is smart enough to treat that number as a text string when it's time to print it with document.writeln .) Figure 6-11. Passing arguments to functions in JavaScript.
|