Default optional parameters allow you to provide a default value when the parameter is not explicitly passed in the function call.
It ensures that the function works even if specific parameters are not provided.
Syntax:
void functionName(parameter1 ,{parameter2 = defaultValue2, parameter3 = defaultValue3, ...}) {
// Function body
}
Lines 1–3: The function is defined with named parameters:
name
andmessage
, both of typeString
in curly brackets{}
having the default values assigned to them.Line 6: No arguments are provided in the first function call
function()
, soname
andmessage
parameters use their respective default values. Therefore, the function prints "Hello, Guest!
" as the default greeting.Line 7: Only the
name
argument is explicitly provided using the named parameter syntax in the second function callfunction(name: 'Jinali')
. The message argument is omitted, so it uses its default value. The function printsHello, Alice!
as the greeting.Line 8: In the third function call
function(message: 'Good afternoon', name: 'Moksha')
,name
andmessage
arguments are explicitly provided using the named parameter syntax. The function recognizes the provided values formessage
andname
, and printsGood afternoon, Moksha!
.