1

I have code that looks like this:

function getTopicOptions(accountID, showTitles, showSelectGroup) {
    "use strict";

    var accountID = store.getItem('AccountID');  
    showTitles = (showTitles !== 'undefined') ? showTitles : 'Y';
    showSelectGroup = (showSelectGroup !== 'undefined') ? showSelectGroup : 'Y';

The idea is that if showTitle and showSelectGroup are not supplied then they will get the default of "Y".

Is there a way do this with function overloading or a way to have the function parameters checked (jslint?) or a way to simplify what I need to do without the undefined check?

4 Answers4

3

You could do something like this:

showTitles = showTitles || 'Y';

or this would work as well, but is more verbose

showTitles = showTitles ? showTitles : 'Y';

I'm not sure where function overloading comes into your question.

codebox
  • 19,927
  • 9
  • 63
  • 81
  • 2
    Note that this is a truthy condition, it will not only fail for `undefined` but also for `false` and `null` – Alexander Sep 28 '12 at 07:29
  • 3
    @Alexander also `0`, `''` and `NaN` – lanzz Sep 28 '12 at 07:30
  • Thanks for the comments. I think in this situation even if it failed with the conditions listed it would be okay as all those conditions could also be another way of not showing the title. –  Sep 28 '12 at 07:32
  • I like this solution a lot too when I'm expecting (and only expecting) an object to be passed. Objects in JavaScript are always truthy. – Peter Sep 28 '12 at 07:33
  • 2
    @Marilou, No offense but I think that using "Y"/"N" here instead of boolean values seems stupid – Alexander Sep 28 '12 at 07:34
1

There is popular default params trick:

var showSelectGroup = showSelectGroup || false;

but it depend on param, if it bool ('', 0 and etc) and looks like showSelectGroup || true you can't set false

Also look at:

Community
  • 1
  • 1
webdeveloper
  • 17,174
  • 3
  • 48
  • 47
0

EDIT

Following is possible

var functionTest = function(argu) {
        argu = argu || 'my argument';//ifargu not passed than 'my argument'
        return argu;
};

alert(functionTest());
// browser alerts "my argument" 

There is no way of function overloading in javascript ,

But if you dont pass the vlaue in function its became undefined vlaue that means you can call the function like

this function

getTopicOptions(accountID, showTitles, showSelectGroup)

can be called like

getTopicOptions(1);

other two value becomes undefined.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

There is an arguments object which is (more or less) an array of all supplied arguments. You can loop through these.

See http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/

Thomas
  • 8,426
  • 1
  • 25
  • 49