views:

61

answers:

2

Hello,

I have a function that I want to pass an argument to, however I want it to default to 0.

Is it possible todo it similarly to PHP, like:

function byMonth(export=0) {

Many thanks

+4  A: 

You can set a default inside, like this:

function byMonth(export) {
  export = export || 0;
  //your code
}
Nick Craver
+4  A: 

Dont do this

function byMonth(export){
  export = export || 0;
  alert(export);
}

Edit:

The previous version has a silent bug, I'm leaving it just as an example of what NOT TO DO.

The problem is, suppose you pass the function the argument false, it will take the default value although you actually called it with an argument.

All this other parameters will be ignored and the default will be used (because of javascript concept of falsy)

  • The number zero 0
  • An empty string ""
  • NaN
  • false
  • null
  • and (obviously) undefined

A safer way to check for the presence of the parameter is:

  function byMonth(export){
      if(export === undefined) export = 0;
  }

Edit 2:

The previous function is not 100% secure since someone (an idiot probably) could define undefined making the function to behave unexpectedly. This is a final, works-anywhere, bulletproof version:

function byMonth(export){
  var undefined;
  if(export === undefined) export = 0;
}
Pablo Fernandez
This is actually better than @Nick's answer because you're using `var`.
Jacob Relkin
@Jacob - It's defined as a parameter :)
Nick Craver
@Nick, Yeah, i guess i was afraid of a global variable override.
Jacob Relkin
@Jacob - That won't happen, it's local to this scope, I'm actually not sure what `var` does here, it might have some re-defining side-effects.
Nick Craver
@Nick, you're right.
Jacob Relkin
Given he wants to default to `0`, I think the author has a known data type here (number, the month index). I think it's perfectly valid to use `export || 0` if you know you're dealing with a number and want `0` in the case it's not passed :) In *some* cases I agree don't do this, but when the case is as specific as this, it's works fine.
Nick Craver
@Nick We can also assume that the user wants a solution that works not only for that single function, but for all cases. Also, maybe the function is just a simple example and not the real thing
Pablo Fernandez
@Nick and don't forget that other users might have the same question (optional params) and land to this page by google for example.
Pablo Fernandez