Trax
Trax

Reputation: 1538

Call function with multiple arguments based on conditional statement

Title says it all I have the following function :

var foo = function(arg1, arg2,arg3) {
    // code
}

I want to do something like :

foo('bar', (x == true ? arg2, arg3 : arg2,arg3))

But I get hit with SyntaxError: Unexpected token , what is the right syntax to do something like this?

Upvotes: 3

Views: 12712

Answers (3)

vinayakj
vinayakj

Reputation: 5681

var foo = function(arg1, arg2,arg3) {
    console.log(arguments)
}
var x = false;
var args = [];
args.push('bar');
x == true ? (function(){args.push('arg2'); args.push('arg3')})() : args.push('arg2');
console.log(args)
foo.apply(this,args)

There are two methods to pass the variable no of arguments to the function.

  1. bind
  2. apply

Use either one as per your need.

Upvotes: 0

It-Z
It-Z

Reputation: 2000

I would go with readability as JCOC611 said...

Yet, the "right" way is using .apply():

foo.apply(this, (x == true ? [arg1, arg2, arg3] : [arg1 ,arg2, arg3]))

Upvotes: 9

JCOC611
JCOC611

Reputation: 19719

I don't think it is worth it to save a few characters. It's much more valuable to have readable code. Just get a minifier/uglyfier, and do this:

if(x === true){
   foo('bar', arg2, arg3);
}else{
   foo('bar', arg2, arg3);
}

Upvotes: 6

Related Questions