Optional parameters

JavaScript has no syntax that allows you to have a default value for a function parameter as you often do in most other languages. This is scheduled for a future version of ECMAScript, but for now you have to take care of this yourself inside the body of your function.

There are several patterns that do the job, but here's a new one. It was suggested to me by Andrea "WebReflection" Giammarchi in his technical review of the upcoming JS4PHP book.

Andrea doesn't remember blogging about this pattern and I don't remember ever seeing it. So here goes.

Say you have a function with all 4 default parameters, mimicking for example PHP's declaration:
function sum($a = 1, $b = 2, $c = 3, $d = 4) ...

function sum(a, b, c, d) {
  // note no `break` needed
  switch (arguments.length) {
    case 0: a = 1;
    case 1: b = 2;
    case 2: c = 3;
    case 3: d = 4;
  }
  return a + b + c + d;
}

Test:

sum();            // 10
sum(1);           // 10
sum(11);          // 20
sum(1, 2, 3, 24); // 30
sum(11, 22);      // 40

Obviously this doesn't work when you have an optional param, followed by a required one, but that's just bad design.

Thoughts?

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile you can find me on twitter - @stoyanstefanov