Optional Arguments
When you define a function that accepts input arguments, you usually must call the function with exactly the number of arguments the function was designed to accept. For example, if you define a function like:
you must call the function with exactly two arguments; Magnitude(3,4) is legal, but Magnitude(3) and Magnitude(3,4,5) both fail.
There are cases where you may want to create functions that accept an abbreviated argument list and use default values for all unspecified arguments. You can do this by supplying default values for each argument in the function declaration as follows:
This function accepts either 1 or 2 input arguments. If you supply only one argument, it defines the value of x; y is set equal to 0. If you supply three arguments, the function fails.
Note that you can truncate the argument list when supplying arguments in a function call, but you cannot skip arguments. For example, if you define Magnitude as follows:
then you can call the function with 1, 2, or 3 arguments. However, if you call the function with an expression like:
you have not caused the function to use its default value for the second argument. Instead, you have set the value of the second argument equal to null. That is, Magnitude(2,,4) is the same as Magnitude(2,null,4).