Tuesday, June 25, 2024 21:22

Table of contents >> Functions > Optional parameters

Optional parameters

When I explained functions and methods parameters, I said that we can use them to send different values that our methods and functions can use in their calculations. You should also know that methods and functions can have optional parameters, parameters with a default value, which can be skipped when calling a method or function.

The way we declare a method or function with optional parameters is to specify a default value in the declaration of those parameters, like this:

In the above code, because we only declared, but not initialized method parameters x and y, they are mandatory. We cannot call SomeMethod(), without providing values for x and y. However, because we also initialized z as 0, this in turn will make it an optional parameter, which can be skipped when invoking SomeMethod(). The following calls are both valid:

In case we don’t provide a value to the optional parameters when we call the method, if and when we use them in our method, the program will use the default value with which they were initialized in the method or function declaration.

The concepts explained in this lesson are also shown visually as part of the following video:

Tags: , , , ,

Leave a Reply

Follow the white rabbit