views:

933

answers:

3

Possible Duplicate:
Is there a better way to do optional function parameters in Javascript?

I would like a javascript function to have optional arguments which I set a default on, which gets used if the value isn't defined. In ruby you can do it like this:

def read_file(file, delete_after = false)
  # code
end

Does this work in javascript?

function read_file(file, delete_after = false) {
  // Code
}
+5  A: 
function read_file(file, delete_after) {
    delete_after = delete_after || "my default here";
    //rest of code
}

Note

This does not work if you want to pass in a value of false or null, in which case you would need to use the method in Tom Ritter's answer.

Russ Cam
I find this insufficient, because I may want to pass in false.
Tom Ritter
I find it's adequate for most situations
Russ Cam
+6  A: 

There are a lot of ways, but this is my preffered method - it lets you pass in anything you want, including false or null. (typeof(null) == "object") Via ParentNode

 function foo(a, b)
 {
   a = typeof(a) != 'undefined' ? a : 42;
   b = typeof(b) != 'undefined' ? b : 'default_b';
   ...
 }
Tom Ritter
+3  A: 

I find something simple like this to be much more concise and readable personally.

function pick(arg, def) {
   return (typeof arg == 'undefined' ? def : arg);
}

function myFunc(x) {
  x = pick(x, 'my default');
}
tj111