0

I have a foo function:

var foo = function(input) {
  console.log(input)
}

And a bar function:

var bar = function(fn, condition) {
  if (condition) {
    fn();
  }
}

I would like to pass foo as an argument of bar like: bar(foo, true);

The problem is that foo must be called executing a parameter. If I use bar(foo('param'), false);, foo will be executed before bar starts and check the condition.

Is there a better solution in JavaScript syntax?

I know that I could modify my bar function to the following, but I don't want to modify the bar implementation:

var bar = function(fn, fnParam, condition) {
  if (condition) {
    fn(fnParam);
  }
}
kimb
  • 15
  • 7

1 Answers1

2

You can use this format: bar(function() { foo(param); },false), unless you need the meta information in the foo function, like name, in which case you need to use the function(fn, paramArray, condition)... method

Note that with new Javascript features, such as Arrow functions, you can write the same thing with bar(()=>foo(param),false), but not all browsers support this syntax.

Siderite Zackwehdex
  • 6,293
  • 3
  • 30
  • 46