Passing a Value to a FunctionYou'll often want to take some information and give it to a function to use. This is called passing the information to the function. For example, look at this function definition: function playBall(batterup) The variable batterup is a parameter of the function. When a function is called, data can be passed into the function. Then, when you're inside the function, that data is in the batterup variable. Functions can be passed just about any data you want to use, including text strings, numbers, or even other JavaScript objects. For example, the batterup variable could be passed a player's name as a text string ("Mantle"), or his number in the lineup (7) (although mixing the two can be a very bad idea until you really know what you're doing). Like all variables, you should give the ones you use as function parameters names that remind you what the variable is being used for. You can have more than one parameter in a function. Just separate them inside the parentheses with commas, like this: function currentScore(hometeam,visitors) We would like to underscore that parameters are variables, and so they can be passed a variety of different values when the function is called. So these code fragments are all equivalent: currentScore(6,4); var homeScore = 6; var visitingScore = 4; currentScore(homeScore,visitingScore); currentScore(6,3+1); For all three examples, once we're inside currentScore(), the value of hometeam is 6, and the value of visitors is 4 (which is great news for the home team). In this example, we'll clean up some of the calculations from Script 3.3 by taking them out of the newCard() function, restating them a bit, and putting them into a function with passed values, in order to make it more obvious what's going on. It all happens in Script 3.4. Script 3.4. By passing values to the setSquare() function, the script becomes easier to read and understand.
To pass a value to a function:
|