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.
-
4Assuming 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.iandotkelly– iandotkelly2014-11-03 14:09:29 +00:00Commented Nov 3, 2014 at 14:09
-
No. This is impossible with JavaScript, or any language for that matter. (as far as my knowledge reaches)Zaenille– Zaenille2014-11-03 14:10:27 +00:00Commented Nov 3, 2014 at 14:10
-
@MarkGabriel Python has optional and named arguments (in which case order does not matter).The Paramagnetic Croissant– The Paramagnetic Croissant2014-11-03 14:13:04 +00:00Commented Nov 3, 2014 at 14:13
-
@MarkGabriel C# has optional and named arguments too.iandotkelly– iandotkelly2014-11-03 14:14:27 +00:00Commented 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.Zaenille– Zaenille2014-11-03 14:18:09 +00:00Commented Nov 3, 2014 at 14:18
2 Answers
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.
2 Comments
someFunc.apply(null, Array.apply(null, { length: 99 }).map(function () { return ""; }).concat(arg100))?undefined would do the job just as well.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)