skip to Main Content

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

2

Answers


  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.

    Login or Signup to reply.
  2. 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});
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search