Positional optional parameters are declared inside square brackets [ ] and are identified by their position in the arguments list.
When calling the function, these parameters can be omitted.
void functionName(parameter1 ,[parameter2, parameter3, ...]) {
// Function body
}
In the case of optional positional parameters, if a value is not passes then it will be assigned a default value of null.
Line 1: The function is defined with two parameters:
name
of typeString
andmessage
of typeString
(optional positional), and check that message parameter is null?Line 2: Inside the function an if statement is used to check if the
message
parameter is notnull
.Line 3: If the
message
is notnull
, it means a value was provided when calling the function, so it prints the concatenated string ofmessage
, followed by a comma and thename
.Line 5: If the
message
isnull
, which means no value was provided formessage
, so it prints a generic greeting of "Hello" followed by thename
.Line 10: Only the
name
argument is provided in the first function callfunction('Alice')
, and themessage
argument is omitted. Therefore, the function printsHello, Alice!
as the default greeting.Line 11: In the second function call
function('Bob', 'Good morning')
,name
andmessage
arguments are provided. The function recognizes the provided message value asGood morning
and printsGood morning, Bob!
.