I have recently learned that you can use a neat switch statement with fallthrough to set default argument values in Javascript:
function myFunc(arg1, arg2, arg3) {
//replace unpassed arguments with their defaults:
switch (arguments.length) {
case 0 : arg1 = "default1";
case 1 : arg2 = "default2";
case 2 : arg3 = "default3";
}
}
I have grown to like it a lot, since not only is it very short but it also works based on parameters actually passed, without relying on having a special class of values (null, falsy, etc) serve as placeholders as in the more traditional versions:
function myFunc(arg1, arg2, arg3){
//replace falsy arguments with their defaults:
arg1 = arg1 || "default1";
arg2 = arg2 || "default2";
arg3 = arg3 || "default3";
}
My inital though after seeing the version using the switch was that I should consider using it "by default" over the ||
version.
The switch fallthough makes it not much longer and it has the advantage that it is much more "robust" in that it does not care about the types of the parameters. In the general case, it sounds like a good idea to not have to worry about what would happen with all the falsy values ('', 0, null, false ...) whenever I have to make a function with default parameters.
I would then reserve the arg = arg || x
for the actual cases where I want to check for truthyness instead of repurposing it as the general rule for parameter defaulting.
However, I found very few examples of this pattern when I did a code search for it so I had to put on my skeptic hat. Why didn't I find more examples of this idiom?
- Is it just now very well known?
- Did I not search well enough? Did I get confused by the large number of false positives?
- Is there something that makes it inferior to the alternatives?
Some reasons that I (and some of the comments) could think of for avoiding switch(arguments.length)
:
Using named parameters passed via an object literal is very flexible and extensible. Perhaps places where more arguments can be optional are using this instead?
Perhaps most of the time we do want to check for truthyness? Using a category of values as palceholders also allows default parameters to appear in the middle instead of only at the end :
myFunc('arg1', null, 'arg3')
Perhaps most people just prefer the very short
arg = arg || "default"
and most of the time we just don't care about falsy values?Perhaps accessing
arguements
is evil/unperformant?Perhaps this kind of switch case fallthrough has a bad part I didn't think about?
Are these cons enough to avoid using switch(arguments.length)
as a staple default argument pattern or is it a neat trick I should keep and use in my code?