11

So I've been doing this for as long as I can remember, but I'm curious if this is really what I should be doing. You write a function that takes a parameter, so you anticipate it to have a value, but if it doesn't, you have a good reason to default it, to say zero. What I currently do is write a helper function:

function foo() { return foo(0); };
function foo(bar) { ... };

I just ran across an instance where I did this and I looked at it oddly for a few seconds before understanding my logic behind it. I come from php where it's trivial:

function foo(bar=0) { ... }

Is there a javascript alternative that I'm not aware of?

Rupesh Yadav
  • 12,096
  • 4
  • 53
  • 70
user280725
  • 293
  • 1
  • 2
  • 7
  • Duplicate of http://stackoverflow.com/questions/148901/is-there-a-better-way-to-do-optional-function-parameters-in-javascript – BGerrissen Sep 08 '10 at 21:40

4 Answers4

17

You can't have overloaded functions in JavaScript. Instead, use object based initialization, or check for the values and assign a default if none supplied.

In your example, the second function foo(bar) will replace the first one.

Here's a function using object initialization.

function foo(config) {
    extend(this, config);
}

where extend is a function that merges the config object with the current object. It is similar to the $.extend method in jQuery, or $extend method of MooTools.

Invoke the function and pass it named key value pairs

foo({ bar: 0 });

The other way to initialize is to look at the supplied values, and assign a default if the value is not given

function foo(bar) {
    bar = bar || 0;
}

This works as long as bar is not a falsy value. So foo(false) or foo("") will still initialize bar to 0. For such cases, do an explicit check.

function foo(bar) {
    bar = (typeof bar == 'undefined' ? 0 : bar);
}
Anurag
  • 140,337
  • 36
  • 221
  • 257
5

In JavaScript, the argument will be undefined if the user didn't pass it in. You can use the || operator to set the value of the argument if it's undefined:

function foo(bar) {
  bar = bar || 0;
  ...
}
Annie
  • 6,621
  • 22
  • 27
  • 5
    you had better check for `bar === undefined` instead of doing this simple test. – jrharshath Sep 08 '10 at 21:43
  • @jrharshath I just figure out `variable===undefined` is wrong just because undefined is actually a undefined variable, not a reserved word. So If you previously assign `undefined=true;` and then test `alert(x===undefined) //returns false` So you should type check using `typeof variable===undefined` – Vitim.us May 15 '12 at 20:31
  • 1
    This answer is wrong, because you can't pass 0 nor false nor null. Exemple: If bar is true by default like this `bar = bar || true` you can't pass false, bar will be always true. – Vitim.us May 15 '12 at 20:39
  • 1
    @Vitim.us `undefined` was fixed ECMAScript 5, [See 15.1.1.3](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf), released 2009 [implementation chart, look for Immutable undefined](http://kangax.github.com/es5-compat-table/) The answer by Annie is wrong because of the reasons you gave above (0,false,null). – some Mar 20 '13 at 02:53
1

The simplest way I know of is test for a value and then set it to a default value if no value is found. I have not come across a catch all one liner yet, this is the best i have got.

If expecting a string value use this. Default will trigger on these values: [ undefined, null, "" ]

function foo(str) {
  str = !!str  ? str  : 'bar';
  ...
}

If expecting a number or Boolean value. This allows 0 and false as values. Default will trigger on [ undefined, null, {}, functions ]

Handy for making values arguments that only accept primitive values like number, boolean and string

function foo(val) {
  val= !!val == val || val*1 ? val : 10;
  ...
}

If you're looking to test for objects such as {}, There is documentation on doing this but it isn't so simple.

Matthew.Lothian
  • 2,072
  • 17
  • 23
0

Hopefully this answers a bit clearer for someone - I ended up using the ol' check for undefined if(typeof functionparameter !== 'undefined') as per:

$.fn.extend({
    doThing: function(stringparameter = 'FooBar!', functionparameter){
        console.log('Here is your string '+stringparameter);
        // Run it if it's been passed through:
        if(typeof functionparameter !== 'undefined') functionparameter();
});
Grant
  • 5,709
  • 2
  • 38
  • 50