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? 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]))
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

I partially disagree with the solution, when there is a specific method (apply) for a function, we should use it.
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.