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;


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.


15 Responses to “Optional parameters”

  1. stoimen Says:

    Looks nice and clean, although it’s difficult to read at first. Like it!

  2. ricktap Says:

    I think anything not obvious is bad code. Although as someone working often with switch cases, I can tell what’s going on, different implementations in other languages make it a mess.
    Ruby i.e. doesn’t use break statements at all and breaks automatically. Of course that’s nothing to worry about for a JS developers, but I think taking those things in to account, makes this an ambiguous answer.

  3. JSSpy » Optional parameters Says:

    [...] Source: http://www.jspatterns.com/optional-parameters/ [...]

  4. JSSpy » Optional parameters Says:

    [...] Source: http://www.jspatterns.com/optional-parameters/ [...]

  5. Chris Heilmann Says:

    I find it irksome to have lots of parameters in a function as you’ll always have to name them sensibly and have issues with omitting some of them. It is bad enough that PHP itself is riddled with that. In JS I tend to have two parameters tops and if it is more, sending an object in makes more sense as it has all of them optional, gives you more obvious naming and reference and makes the order of no importance.

  6. Dan Says:

    I understand that it might be hard to read at first, but so are many other design patterns; such at the Template pattern or Visitor pattern. The whole idea of defining a pattern is so it becomes recognizable and solves a problem efficiently. This solution is elegant and quickly recognizable once the pattern has been learned. I say well done.

  7. Flávio Medeiros Says:

    What about this:

    // https://gist.github.com/Sigmus/4773187

    function sum(a, b, c, d) {
    a = a || 1;
    b = b || 2;
    c = c || 3;
    d = d || 4;
    return a + b + c + d;

  8. Stephen Says:

    @Flavio will sum(0, 0, 0, 0) work?

  9. Flávio Medeiros Says:

    I see; it doesn’t. Thanks.

  10. Werner Gaskamp Says:

    hey there and thank you for your info – I’ve definitely picked up anything new from right here.

    I did however expertise a few technical points using this website, since I experienced to reload the web site lots of times previous to I could get it to
    load correctly. I had been wondering if your web hosting is OK?
    Not that I’m complaining, but slow loading instances times will sometimes affect
    your placement in google and can damage your high quality score if ads and
    marketing with Adwords. Anyway I am adding this RSS to my email and could look out for much more of your respective exciting content.
    Ensure that you update this again very soon.

  11. Men Parajumpers SCHROEDER Says:

    Websites are able to target a vast variety of clients. Yes,PJS Outlet, Jim Chanos had a hand in bringing Enron to light, but given the work Fortune Bethany MacLean and others did on the parajumpers kodiak women at the same time, Enron would have blown up on schedule even if he hadn shorted a single share. As we join him to witness the insertion of the Soul known as Wanderer into her eighth incarnation – her first as a human, having previously been a bat, a Parajumpers Jassen, a bear,Women Paraju

  12. asos target promo code august 2012 Says:

    KARMALOOP – Save 20 percent on any order with Rep – Code THEHUSTLE.
    ” The scent wows the actual ladies who vote this particular cologne as tops among male colognes available in the market. The health supplement industry looks to have a item for a slew of supposed targets: muscle mass expansion, longevity, disease prevention, and many others.

  13. Cheap Louis Vuitton Says:

    Forcment, les hommes en sont venus christian louboutin guerilla affirmer leur style et leur personnalit par leurs souliers. Nous pouvons apprendre quelque chose Louis Vuitton Handbags Outlettuhfeih1234 propos d’un homme en regardant quels souliers il porte. Avec la dmocratisation de la mode, tout le monde peut avoir le mme jeans et tee shirt de chez Gap. On the Memphis Grizzlies doesn mind. Based on him his clothing is a method to introduce a lot more of his personality to fans.remarked that my

  14. Furla Outlets Online Says:

    Elvis homage designers consider the actual phase within Saginaw with regard to circular 1During previous many years, rivals just sang 1 tune about the starting evening prior to finalists had been selected, this season the actual stress is actually away. Just about all 2014 Elvii be a part of each evenings from the display.Whilst finalists, as well as eventually a success, tend to be selected through idol judges Sunday evening, the actual Elvis homage designers just about all obtain the opportuni

  15. Louis Vuitton Sunglasses Says:

    Circles launched through halfway homeMight ’07, 2010EXCELLENT DROPS, Veterans administration. (AP) Gilbert Circles showed up house from the halfway home Fri early morning, getting finished 1 a part of their consequence with regard to getting weapons to the Wa Wizards locker space. He or she attempted many times in order to strike the actual mixture about the keypad in order to key in their gated front yard. Following a number of unsuccessful efforts, he or she muttered “Alrighty, inch obtained f

Leave a Reply