I am trying to create a function in JS that is taking a lot of arguments but does not always use all of them. What I would like to do is define which argument I am putting a refrence in for. This is what I am thinking but not working like I would like it to.
function foo(arg1, arg2, arg3){
let arg1 = arg1;
let arg2 = arg2;
let arg3 = arg3;
}
foo(arg2:'sets value of arg2');
I would like to be able to skip putting in an argument for the first position and only pass info for the second argument. How can I do this?
-
Also have a look at named arguments in JavaScriptJonas Wilms– Jonas Wilms2018年07月28日 20:40:06 +00:00Commented Jul 28, 2018 at 20:40
-
Thank you to everyone's input, it helped me in making this. github.com/dambergn/js-password-generatordambergn– dambergn2018年07月28日 21:18:32 +00:00Commented Jul 28, 2018 at 21:18
3 Answers 3
You could spread syntax ... a sparse array with the value for the wanted argument without changing the function's signature.
function foo(arg1, arg2, arg3){
console.log(arg1, arg2, arg3)
}
foo(...[, 42]);
Or use an object with the key for a specified element
function foo(arg1, arg2, arg3){
console.log(arg1, arg2, arg3)
}
foo(...Object.assign([], { 1: 42 }));
Comments
Try this:
It would require the caller to pass an object.
function foo({arg, arg2}={}) {
let arg_1 = arg;
let arg_2 = arg2;
console.log(arg_1);
console.log(arg_2);
// Code
}
foo({arg2: 2});
if you need to set the default parameters you can do it this way function foo({arg = '', arg2 = ''}={})
1 Comment
You can pass in null as some of the parameters if they are not needed.
function foo(arg1, arg2, arg3){
console.log(arg1, arg2, arg3);
}
foo(null, 30, null);