2

I'm new to javascript and I was learning higher-order functions where I learned about passing functions as arguments to other functions. How can I pass a function with arguments to a function?

I want to pass the function's arguments when passing the function as parameter to the main function.

example :

function fubar(a,b,fun(c,d)){
//execute here
}

and not like this

function fubar(a,b,fun()){
  fun(a,b)
}
Varun r
  • 85
  • 1
  • 1
  • 6
  • It's unclear how the code in your question relates to the actual question. Your code shows a function definition. If you're defining a function argument, just give it an argument name, ie `function fubar(a, b, fn) { ... }` – Phil Sep 04 '19 at 03:28

3 Answers3

4

Here's an example, just pass it like a regular argument, no specific syntax is required :)

// define the function argument like a regular argument
function fubar(a, b, fn){
  // call that argument like a function
  return fn(a, b);
}

// sample function 
function add(c, d){
  return c + d;
}

// pass the "add" function like a regular argument
let result = fubar(1, 2, add);

console.log(result);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
1

You just need to pass the name of the function as the parameter, just like another variable.

for example :

foobar(5, 10,  baz,  ham);

function foobar(a, b, fn1, fn2){
    ...
    fn1(); // call the baz function.
    res = fn2(a,b); // calls ham func with a and b as parameter
    console.log(res) 
    ...
}

function baz(){
   console.log("Inside the Baz function ");
}

function ham(s,t){
   console.log(s, t);
   return s+t;
 }
Mukul Kumar Jha
  • 1,062
  • 7
  • 19
0

If you're asking how to pass a function that will execute with some pre-determined arguments, you can do so using another function.

For example

const a = 'a'
const b = 'b'
const c = 'c'
const d = 'd'

function fubar(a, b, fn) {
  console.info('func:', a, b, fn()) // executing "fn()" here
}

function fun(arg1, arg2) {
  console.info('fun:', arg1, arg2)
  return 'return value from fun' // just an example so you can see it in fubar()
}

fubar(a, b, () => fun(c, d))

Here, () => fun(c, d) is an self-contained, anonymous arrow function (or "lambda") that when called, will execute fun(c, d).

Phil
  • 157,677
  • 23
  • 242
  • 245