I have a function example(arg1,arg2,arg3,arg4) and the function uses arg4 for something. Is there a way for me to skip the other arguments instead of having them as unused variables.
I tried example(,,,arg4) but it does not work
You could create a wrapper function that takes an object instead of four arguments, and translates that to a call of the original function. Then you can target the arguments you wish to provide by name:
function example(arg1,arg2,arg3,arg4) {
console.log(arg1,arg2,arg3,arg4); // Mock implementation: just prints the four arguments
}
// Wrapper that takes object instead of separate arguments
function example2({arg1, arg2, arg3, arg4}={}) {
return example(arg1, arg2, arg3, arg4);
}
// Example use: only providing arg4:
example2({arg4: 1});
If you're looking for a compact way to insert a bunch of null values into your function arguments, maybe this would work for you.
Create a helper function which generates an array of null values.
const no = howMany => Array(howMany).fill(null);
Then when you call your function, just spread the result of this helper into your arguments.
i.e.
//instead of
example(null, null, null, someVar4);
//do
example(...no(3), someVar4);
If you have control over the construction of this function you're using, there are better ways to accomplish a task like this, but as a direct answer to the question you asked, hopefully this helps :) If you'd like any explanation / clarification, please ask.
You can do this if you change your params and the way they are passed. Look at this example:
function test({ a = null, b = null, c = null } = {}) {
a ? console.log({ 'a': a }): ''
b ? console.log({ 'b': b }): ''
c ? console.log({ 'c': c }): ''
}
// Calling the function with all parameters
test({ a: 1, b: 2, c: 3 });
// Calling the function with only one parameter
test({ b: 'Only pass b' });
// Calling the function with no parameters
test();
null, etc.) depending on how you have implemented the function. That being said, a better approach would be to change the function to accept an object whose properties you can include/omit as desired.