4

I was wondering what the best practice would if I had function that accepted 4 params a,b,c,d but I had a situation where I didnt have a value to pass in for param c but needed to pass in a value for param d so:

function myFunction(a,b,c,d) {
 //...
}

myFunction(paramA, paramB, '', paramD);

do you pass in undefined for param c and then do a check inside the function or something like that?

styler
  • 15,779
  • 23
  • 81
  • 135

5 Answers5

6

Better is to use Object for me:

function myFunction( options ) {
 //...
}

myFunction({
    paramA: "someVal",
    paramD: "anotherVal"
});

Then in function you can check for empty params and pass defaults:

function myFunction( options ) {
    options = options || {};
    options.paramA = options.paramA || "defaultValue";
    // etc...
}    
antyrat
  • 27,479
  • 9
  • 75
  • 76
1

You can make any optional parameters be furthest to the right in your function signature, that way you can just leave them off when you call the function.

function myFunction(a, b, d, c) {
    // ...
}

myFunction(1, 2, 3, 4);

// call without 'c'
myFunction(1, 2, 3);
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
1

I find setting a default value if it is undefined to be the most simpelist/reliable solution

function myFunction(a,b,c,d) {
    if (typeof a === 'undefined') { a = 'val'; }
    if (typeof b === 'undefined') { b = 'val'; }
    if (typeof c === 'undefined') { c = 'val'; }
    if (typeof d === 'undefined') { d = 'val'; }
}
Dan
  • 425
  • 2
  • 11
  • Isn't just `if (a === undefined) { a = 'val'; }` cleaner? – Strille Jun 11 '13 at 12:35
  • Using the `undefined` global isn't necessarily the most secure way since globals can be overwritten. `typeof a === 'undefined'` is the most fullproof IMHO. – Dan Jun 11 '13 at 12:41
  • Fair point. I do wonder if it's really worth worrying about undefined being overwritten though. Also, in strict mode, trying to define undefined will throw an exception. So the more common strict mode becomes the more unlikely the scenario becomes. – Strille Jun 11 '13 at 14:50
0

Pass null as the param you don't have. undefined is a bit more specialized, although they will work the same way.

Maxim Kumpan
  • 2,545
  • 2
  • 19
  • 23
0

If uou know what parameter was passed you can use parameter 'arguments' of function. For example:

 function example(a, b, c, d) {
 if (arguments.length < 4) {
   paramC = defaultParam; // something default value for passed C
   }
 }
Any Mitchel
  • 183
  • 2
  • 9