Skip to content Skip to sidebar Skip to footer

Skip Arguments In A Javascript Function

I have a function like this: function foo(a, b, c, d, e, f) { } In order to call this function only with an f argument, I know I should do: foo(undefined, undefined, undefined, un

Solution 1:

Such:

foo(undefined, undefined, undefined, undefined, undefined, arg1, arg2);

.is equal to:

foo(...Array(5), arg1, arg2);

.or:

foo(...[,,,,,], arg1, arg2);

Such:

foo(undefined, arg1, arg2);

.is equal to:

foo(...Array(1), arg1, arg2);

.or:

foo(...[,], arg1, arg2);

Such:

foo(arg1, arg2);

.is equal to:

foo(...Array(0), arg1, arg2);

.or:

foo(...[], arg1, arg2);

Solution 2:

You could use apply:

foo.apply(this, Array(5).concat([theFValue]));

In this case, 5 is the amount of parameters you want to skip.

Wrap that in a function:

function call(fn, skipParams, parameter) {
    fn.apply(this, Array(skipParams).concat([parameter]));
}

call(foo, 5, theFValue);

However, in that case the scope of this is different, so you may need to pass that, too:

function call(fn, skipParams, parameter, thisArg) {
    fn.apply(thisArg, Array(skipParams).concat([parameter]));
}

call(foo, 5, theFValue, this);

Then again, this implementation only allows 1 parameter to be passed. Let's improve that:

function call(fn, skipParams, parameters, thisArg) {
    fn.apply(thisArg, Array(skipParams).concat(parameters));
}

call(foo, 5, [theFValue, theGValue, theHValue], this);

That's starting to get a "little" verbose. It also doesn't handle missing parameters after the first parameter that well, unless you want to pass undefined:

call(foo, 5, [theFValue, theGValue, theHValue, undefined, theJValue], this);

Or, something completely different:

var _ = undefined;
foo(_,_,_,_,_, theFValue);

On a more serious note:

Your best option to deal with optional parameters, is to change the way you're handling parameters. Simply pass an object:

function foo(parameters){
    //do stuff with `parameters.a`, `parameters.b`, etc.
}

foo({c:1, g:false});

This approach doesn't suffer from any of the drawbacks in the earlier examples.

Solution 3:

A better way to deal with optional arguments is to pass an object whose attributes you look up:

functionfoo(options) {
    var a = options.a,
        b = options.b,
        c = options.c,
        d = options.d,
        e = options.e,
        f = options.f;
}

foo({ f: 15 });

Solution 4:

Skip function:

constskip = (num) => newArray(num);

Skipping beginning params:

foo(...skip(4), f);

Skipping end params:

foo(f, ...skip(4));

Skipping middle params:

foo(f, ...skip(4), f2);

Solution 5:

If you will pass an object with a property name f so you can use destructuring assignment with ES6 syntax like this:

functionfoo({ f }) {
  console.log(f);
}
    
foo({ g: 5, f: 10 });

Post a Comment for "Skip Arguments In A Javascript Function"