I keep a pretty close eye on the searches that bring people to this blog. A lot of you are searching for how to sort in JavaScript (I’ll have to go into more detail on sorting soon). And a whole mess of you want to know about missing and default parameters.
I’m going to take another shot at the default parameter problem. I gave a solution that adds just one line of code per function, but it requires you to pass all parameters in a single object. I’ll adapt that solution to better handle the normal way of passing JavaScript parameters.
Really quickly, let’s talk about JavaScript parameters.
- When you pass in fewer than the expected number of parameters, the missing ones come in as undefined.
- When you pass in more than the expected number of parameters, the excess ones can be slurped out of the arguments pseudo-array. This array-like variable has the length method, but is missing other array methods.
- A common way to implement default parameters is with a series of statements like this: a=a || 1; The problem with such a statement is that so many different values evaluate to false that it’s easy to make a mistake and prevent a valid number like 0 from coming through.
- A better way to implement default parameters is like this: if (a===undefined) a=1;
- Another common way is if (a==null) a=1; This works pretty well because null and undefined are loosely equal to each other, but other falsy values aren’t equal to either of them.
Let’s modify my defaultHandler from my previous post on the subject so that it works with arrays instead of objects.
defaultHandler=function(defaults,params) { var i; for (i=0;i<defaults.length;i++) { if (params[i]!==undefined) { defaults[i]=params[i]; } } return defaults; }
Choose Your Poison
You now have a couple choices on how to use it. After the default handler is called, the array params will hold all your parameters in order.
function test(a,b,c) { var params=defaultHandler([1,"banana",3],arguments); console.log(params); }
If you really want to, you can stuff the values back into the original named parameters…
function test(a,b,c) { var params=defaultHandler([1,"banana",3],arguments); a=params[0]; b=params[1]; c=params[2]; console.log(a,b,c); }
It’s a shame there’s no way to automate that stuffing of the parameters back into the original variables, isn’t it?
Ah, but there is. In fact, the whole process can be cleaned up with a bit of metaprogramming and some introspection. But that’s for Episode VI.
Note: This is the second post on default parameters. I took a cue from George Lucas on its numbering to try to get some search hits from the Star Wars zealots.