Providing a Default Parameter
Problem
You want to specify a default value for a parameter if no argument value is given when a function is called.
Solution
Use the new ECMAScript 6 (ES 6) default parameter functionality:
function makeString(str, ldelim = "'", rdelim = "'") { return ldelim + str + rdelim; } console.log(makeString(169)); // "'169'"
EXPLAIN
One of the biggest gaps in JavaScript is the lack of a default parameter. Yes, we can
emulate the same functionality, but nothing is simpler and more elegant than having
support for a default parameter built in.
The use is simple: if one or more arguments can be optional, you can provide a default
parameter using syntax like the following:
ldelim = "'"
Just assign the default value (in whatever data type format) to the parameter. The default parameter functionality can be used with any parameter. To maintain the proper argument position, you can pass a value of undefined in the argument:
console.log(makeString(169,undefined,"-")); // "'str-"
At the time I wrote this, only Firefox had implemented default parameter functionality. To ensure future compatibility, test the parameter for the undefined value and adjust accordingly:
function makeString(str, ldelim="'", rdelim="'") { ldelim = typeof ldelim !== 'undefined' ? ldelim : "'"; rdelim = typeof rdelim !== 'undefined' ? rdelim : "'"; return ldelim + str + rdelim; }
No comments:
Post a Comment