3

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?

1
  • What are you actually trying to achieve?
    – PM 77-1
    Commented Jul 11, 2015 at 19:42

3 Answers 3

9

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]))
6

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);
}
1
  • I partially disagree with the solution, when there is a specific method (apply) for a function, we should use it.
    – zakir
    Commented Dec 23, 2019 at 13:25
0
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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.