0

I just wondering to find a keyword or a solution so that I can further find and fix my own problem, so basically, I wanted to call a function but from a function argument, like this.

var arg = function() {/*do something*/};

function do(arg) {
  arg();
}

do(arg);

But I want to put multiple functions on it, but not constant, it sometimes can be 1 function, or sometimes 2 functions or more, is there any solution that I can take? or a keyword to I start searching with? I already searched the internet but I could not find what I want.

1
  • Depending on what you are trying to accomplish, a pipeline might be helpful. Or you can just pass in an array of functions as an argument. More information on the use case would be helpful. Commented Aug 28, 2018 at 3:31

3 Answers 3

2

You could use some really cool new feature called rest parameters. Here is an example.

function callMultiple(...fn) {
 fn.forEach(fn => fn());
}

function FnOne() {
 console.log('function one called');
}

function FnTwo() {
 console.log('function two called');
}

callMultiple(FnOne, FnTwo);

Now callMultiple can take any number of functions. MDN reference

Sign up to request clarification or add additional context in comments.

Comments

2
function doFn(){    
   for(var i = 0; i < arguments.length; i++) arguments[i]();
}

One line ES6:

  var doFn = (...args) => args.forEach(fn => fn());

PD: ´do´ is a reserved word, you should use diffetent variable name.

Comments

1

What you need to do to your do() function is this:

function do(args) {    
    for (var i = 1; i <= args.length; i += 1) {
        args[i]();
    }
}

This would fix your problem. However, you should know that do is a JavaScript keyword, so you should avoid using it as a variable or function of your own.

EDIT: You must include anything you're passing to your function, so you need to add the args parameter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.