Search code examples
javascriptsyntaxparametersoptional-parametersellipsis

What is the equivalent of Lua's ellipsis in JavaScript?


In Lua, a function like this would be valid:

function FuncCallHack(Func, ...)
    return Func(...)
end

Is there a way I could do this in JavaScript? ... means "all unindexed parameters in the form of an ungrouped array" to those unfamiliar with Lua. I have tried ... in JavaScript, and it appeared to be nonfunctional, and as Google doesn't like searching for special characters, it's not much help.


Solution

  • JavaScript has the arguments pseudo-array and the apply function; you can do that like this:

    function FuncCallHack(Func) {
        return Func.apply(this, [].slice.call(arguments, 1));
    }
    

    here's how that works:

    1. arguments - This is a pseudo-array containing all of the arguments passed to the function by the calling code (including the format argument Func).

    2. [].slice.call(arguments, 1) is a way to get an array of all of the arguments except the first one. (It's a common idiom. It works by applying the Array#slice method to the arguments pseudo-array, using Function#call [which is a lot like Function#apply below, it just accepts the args to pass on differently].) Sadly, arguments itself doesn't necessarily have a slice method because it's not really an array.

    3. Then we use the Function#apply method (all JavaScript functions have it) to call Func using the same this value that was used for the call to FuncCallHack, and passing on all of the arguments except Func to it.

    You could also define it slightly differently:

    function FuncCallHack(Func, args) {
        return Func.apply(this, args);
    }
    

    ...which is still really easy to use:

    FuncCallHack(SomeFunction, [1, 2, 3]);
    // Note this is an array --^-------^