So far, the functions we’ve created execute a task without an input. However, some functions can take inputs and use the inputs to perform a task. When declaring a function, we can specify its parameters. Parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.
Let’s observe how to specify parameters in our function declaration:
In the diagram above,
calculateArea(), computes the area of a rectangle, based on two inputs,
height. The parameters are specified between the parenthesis as
height, and inside the function body, they act just like regular variables.
height act as placeholders for values that will be multiplied together.
When calling a function that has parameters, we specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments. Arguments can be passed to the function as values or variables.
In the function call above, the number
10 is passed as the
6 is passed as
height. Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.
rectHeight are initialized with the values for the height and width of a rectangle before being used in the function call.
By using parameters,
calculateArea() can be reused to compute the area of any rectangle! Functions are a powerful tool in computer programming so let’s practice creating and calling functions with parameters.
sayThanks() function works well, but let’s add the customer’s name in the message.
Add a parameter called
name to the function declaration for
name as a parameter, it can be used as a variable in the function body of
name and string concatenation, change the thank you message into the following:
'Thank you for your purchase '+ name + '! We appreciate your business.'
Copy and paste the above message into your code.
A customer named Cole just purchased something from your online store.
sayThanks() and pass
'Cole' as an argument to send Cole a personalized thank you message.