Parameters are super helpful in JavaScript because they allow values to be passed into a function when the function is called. See the Basic Functions tutorial for more on how parameters work.
When you define a function with parameters, the parameters have a default value of undefined
. Only when you call the function with arguments do the parameters override that default and take on the desired values. The example below prints out the value of a parameter for both cases – with and without an argument.
Sometimes we want something other than undefined
as the default for our parameters. For example, in the program above, we may want the function to print “Hello” by default if no arguments are passed in.
Setting different values as defaults for our parameters is easy to do, and it’s done in the function declaration statement. When listing your parameter, include an assignment statement for it!
Instead of
Now it’s
Below is the same program as before, but with the addition of our new default. Notice how it changes the output when there are no arguments in the call statement!
In many cases, our functions have more than one parameter. How do we set defaults in this case? It’s the same – we just include an assignment statement for each parameter that needs a default.
You can even have some parameters with no new defaults mixed in those that have them!
While technically you can list the parameters in any order, the general best practice is to list those without defaults first. This reduces the risk of them being left as undefined
.
Take a look at the updated example below to see how these functions work with different arguments sent in!
Take a look at what happens when we pass the value of undefined
in as an argument for a parameter that has a custom default. What ends up being the output?
When you run the program, you’ll notice that when we pass the value of undefined
as an argument, the parameter is assigned the default value assigned in the declaration. This technique is helpful when you want to pass an argument to a parameter later in the list, bypassing earlier ones.
A function can even have parameters that are assigned the values of other parameters that occur earlier in the list. Remember though, these are default values, so any passed in arguments will overwrite them.
Now it’s your turn. Try making functions and assigning default values to your parameters. Here are a few ideas to try: