0

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?

asked Jul 28, 2018 at 20:04
2

3 Answers 3

1

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 }));

answered Jul 28, 2018 at 20:08
Sign up to request clarification or add additional context in comments.

Comments

0

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 = ''}={})

answered Jul 28, 2018 at 20:12

1 Comment

If it helped you, make the right answer to help those in need, but it was a pleasure
0

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);

answered Jul 28, 2018 at 20:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.