Expressions as Default Values
Learn how to use expressions as default parameters, compute the value of default parameters from other parameters, and use the default value for rest parameters.
We'll cover the following...
The default values are not limited to literals. Expressions are welcome as well, and which is quite powerful. Kudos to JavaScript for that.
In the following code, the fileTax()
function needs a filing date. If the caller does not provide it, the current date of execution is assumed as the default value.
'use strict';//START:CODEconst fileTax = function(papers, dateOfFiling = new Date()) {console.log('dateOfFiling: ' + dateOfFiling.getFullYear());};//END:CODE//START:CALLfileTax('stuff', new Date('2016-12-31'));fileTax('stuff');//END:CALL
The call to this function in line 11 verifies the behavior of the expression in the default value.
- In the first call, in line 10, we pass the last day of the year 2016 as the second argument.
- However, in the second call, we leave it out. As you can see from the output, the expression was evaluated on call and the current year is used.
📝Note: The value of the expression used for the default value is evaluated at the time of the call.
Compute default parameters from regular parameters
The expression that evaluates a default value for a parameter may use other parameters to the left. This gives us the ability to compute the default value ...