Chapter 5. Arguments: passing data to functions
This chapter covers
- Defining functions with parameters, ready to accept data
- Calling functions, passing in data with arguments
Functions are an essential means of organization; you write them once and use them many times. But so far, your functions have been tied to the values of variables around them. It’s time to set your functions free, letting them name their own variables and passing them the data they need.
The functions you’ve used up to now have relied on variables declared and assigned values elsewhere in the program. In the following listing, the showMessage function relies on a variable called message, declared outside the function definition.
Listing 5.1. Relying on a variable outside the function (http://jsbin.com/taqusi/edit?js,console)
In the showMessage function definition, you use a variable called message. The message variable has to exist for the function to do its job. If you change the name of the variable, the function breaks. If message is renamed msg, as shown in the next listing, and the program is run on JS Bin, you should get an error something like this: “Reference error: Can’t find variable: message.” (Different browsers may give slightly different error messages.)