Search code examples
javascriptfunctionsimultaneous-calls

Is it possible to call two functions at the same time with one set of arguments?


Out of curiosity, is it possible to call two functions at once?

For example, here is some pseudo code:

// custom logging function:
function custom_log(string) {
  console.log(string);
}

(console.log && custom_log)("Hello World.");

If it's possible how?


Solution

  • No, you can't say "here are two functions, here's one set of arguments, call them both with the same arguments". But you can pre-define the arguments in a variable and pass that to both functions, which is probably the most concise if you use object destructuring for your parameters:

    function custom_log({output, errorVal}) {
      console.log(output);
      console.error(errorVal);
    }
    const args = {
        output: 'Hello, world',
        errorVal: 'Some error happened'
    };
    console.log(args);
    custom_log(args);
    

    You could also just create a helper function that iterates through an array of passed functions and calls them all:

    function callAllWith(functionList, ...args) {
       functionList.forEach(fn => fn(...args));
    }
    callAllWith([console.log, custom_log], 'Hello, world!');