3

Let's say I have this :

function concatenate(a, b, c) {
    // Concatenate a, b, and c
}

How do I handle those calls ?

x = concatenate(a)

x = concatenate(a, b)

x = concatenate(a, c)

How can I make my function aware of the parameter I gave to it ?

4 Answers4

7

Any unfilled argument will be undefined.

concatenate(a, c) is equivalent to concatenate(a, b). You cannot pass the third parameter without passing the second; but you can pass undefined (or null, I suppose) explicitly: concatenate(a, undefined, c).

In the function, you can check for undefined and replace with a default value.

Alternately, you can use an object argument to imitate keyword arguments: concatenate({a: a, c: c}).

Amadan
  • 191,408
  • 23
  • 240
  • 301
3

Just use arguments array-like object:

function concatenate() {
  var result = '';
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}
vp_arth
  • 14,461
  • 4
  • 37
  • 66
2

from ES6/ES2015 on you can do similar as in php:

function concatenate(a, b = false, c = false) {
    // Concatenate a, b, and c
}

for the older versions, you can do:

function concatenate(a, b, c) {
   if( typeof b !== 'undefined' && typeof c !== 'undefined') {
    // code when a, b and c are defined
   } else if ( typeof b !== 'undefined' && typeof c == 'undefined') {
    // code when a and b are defined
   } else {
   // code
   }

}

I am sure there is a better approach too, but should work.

Andrej
  • 74
  • 3
2

Use the ES6 rest parameters syntax to get an array of arguments. Then simply join its items to retrieve the concatenated string.

concatenate(a);
concatenate(a, b);
concatenate(a, c);

function concatenate(...args){
  // for old browsers
  // `...args` is an equivalent of `[].slice.call(arguments);`
  return args.join('');
}
Lewis
  • 14,132
  • 12
  • 66
  • 87