July 19, 2010

Default function formal parameters in Javascript

Having been programming quite a bit in Ruby and PHP lately, I have gotten used to default formal parameters. This is when you can call a function and omit some of the parameters, the function then assigns pre-defined default values when evaluating those parameters.

It's quite handy at times and helps keep the code succinct and clean.

To see what I mean, in ruby for example you would do the following:

  def a_function(a_param = default_value)
    ...
  end

Later on, the function above could be called in any of the following ways:
  # call function with default param values
  a_function()

  # or specifying a value for the param
  a_function("foo")

In order to achieve the same in Javascript the following is recommended:
  def a_js_function(a_param) {
    var a_param = a_param || default_value;
  }

With the above, you can now call your Javascript function in any of the following ways depending on what you're looking at achieving:

  // call function with default param values
  a_js_function();

  // specify a value for that parameter
  a_js_function("foo");

Note that you can apply the above to all the required parameters of your Javascript function.

That's it!

No comments:

Post a Comment