The syntax to set the default parameter value for a function is:
function functionName(param1=default1, param2=default2, ...) {
// function body
}
Example 1: Set Default Parameter Value For a Function
Output
20 12 8
In the above example, the default value of x is 3 and the default value of y is 5.
sum(5, 15)- When both arguments are passed,xtakes 5 andytakes 15.sum(7)- When 7 is passed to thesum()function,xtakes 7 andytakes the default value 5.sum()- When no argument is passed to thesum()function,xtakes the default value 3 andytakes the default value 5.
Example 2: Using Previous Parameter in Another Parameter
Output
22 32
You can also pass a parameter as the default value for another parameter.
In the above program,
- When 10 is passed to the
calculate()function,xbecomes 10, andybecomes 12 (thesumfunction returns 22). - When no value is passed to the
calculate()function,xbecomes 15, andybecomes 17 (thesumfunction returns 32).