1

Theoretically speaking, let's say I have a function that takes 100 parameters and I only want to use 1 of these, and it's the 100th one. Instead of writing 99 empty strings before I can pass the 100th one, is there an easier way of doing this? I know you should never have 100 parameters but I got curious if this is even possible.

5
  • 4
    Assuming you should ever do this - which you should not, you should use an object with named properties as your argument(s) - you can use 'null' for the spaceholders. Commented Nov 3, 2014 at 14:09
  • No. This is impossible with JavaScript, or any language for that matter. (as far as my knowledge reaches) Commented Nov 3, 2014 at 14:10
  • @MarkGabriel Python has optional and named arguments (in which case order does not matter). Commented Nov 3, 2014 at 14:13
  • @MarkGabriel C# has optional and named arguments too. Commented Nov 3, 2014 at 14:14
  • Yes, but you have to indicate the variable/key name, which would be the JavaScript equivalent of JSON usage as an argument, which uses keys. Commented Nov 3, 2014 at 14:18

2 Answers 2

2

Theoretically, yes, there is a way of doing this. It uses Function.prototype.apply, which allows you to use an array to provide the parameters for a function call.

So if our function was called someFunc, you could do this:

var params = Array(99); // array with 99 undefined parameters
params.push('foo'); // add the 100th parameter

someFunc.apply(null, params);

As you say, though, this is a seriously bad idea. A much better approach is to use an object with named values.

Sign up to request clarification or add additional context in comments.

2 Comments

How about someFunc.apply(null, Array.apply(null, { length: 99 }).map(function () { return ""; }).concat(arg100))?
@AaditMShah Yes, if empty strings are required. I presumed undefined would do the job just as well.
1

Use parameter objects - you can easily set defaults and override what you want with the parameter

var foo = myFunction({foo:'bar', bar:25})

Google parameter objects, eg Passing Default Parameter Objects in JavaScript

(but if you've got more than 3 or 4 parameters you might have a more serious problem)

1 Comment

Didn't even think of using objects, but at least now I know. Thank you!

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.