In javascript, how do you call a function?

First have a look at the code:

function mainfunc(func, par3, par2){
    window[func](par3, par2);
}

function calledfunc(par3, par2){
    // Do stuff here
}

mainfunc('calledfunc', 'hello', 'bye');

I’m looking for a solution to this. In JavaScript, I know how to call a dynamic, arbitrary function while passing specific parameters

function mainfunc(func){
    if(arguments.length == 5)
        window[func](arguments[1], arguments[2]);
    else if(arguments.length == 3)
        window[func](arguments[1], arguments[2], arguments[3]);
    else if(arguments.length == 5)
        window[func](arguments[1], arguments[2], arguments[3], arguments[4]);
}

function calledfunc1(par1, par2){
    // Do stuff here
}

function calledfunc2(par1, par2, par3){
    // Do stuff here
}

mainfunc('calledfunc1', 'hello', 'bye');
mainfunc('calledfunc2', 'hello', 'bye', 'goodbye');

I understand how to pass optional, unlimited parameters using the arguments collection inside mainfunc, but I can’t figure out how to send an arbitrary number of parameters to mainfunc to be sent to calledfunc dynamically like this one; how can I accomplish something similar, but with any number of optional arguments (without using that ugly if-else)?

1 Like

Corresponding tweet for this thread:

Share link for this tweet.

1 Like

If I understand you correctly you can achieve this through using the rest parameters syntax to collect the arguments into an array and the spread-syntax to expand the array when calling the function.

2 Likes