Home > Software design >  Pass a function with parameter as an argument to another function in JavaScript
Pass a function with parameter as an argument to another function in JavaScript

Time:07-26

I am a beginner. I am trying to do something like this -

function write(x, y, z) {
  x();
  console.log("This is foo: ", y, z);
}
var b = 32,
  c = 92;
function a(d) {
  console.log("This is d from a:", d);
  return d;
}
write(a(12), b, c);

And I am getting an Error below -

caspio-common.js:73 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at HTMLDocument.<anonymous> (caspio-common.js:73:26)
at f_dataPageReadyEvent.dispatchEvent (<anonymous>:1:523)
at f_dataPageReadyEvent.init (<anonymous>:1:91)
at new <anonymous> (<anonymous>:2:34)
at <anonymous>:1:1
at f_dpLoadObj.addScriptElement (...

My question is how can I run x(x) with parameter inside write function.

Thank you

CodePudding user response:

You cannot call x because you did not pass the function itself but the returned value of a function as the parameter.

write(a(12), b, c);
// a(12) -> returns 12 which is not a function and thus not callable

One solution to make this work is wrapping the function call into another function.

write(function() {
    a(12);
}, b, c);

Or use this commonly used syntax.

write(() => a(12), b, c);

Full working example

function write(x, y, z) {
  x();
  console.log("This is foo: ", y, z);
}

var b = 32,
  c = 92;

function a(d) {
  console.log("This is d from a:", d);
  return d;
}

write(() => a(12), b, c);

CodePudding user response:

check this

function pass1(value){
  return ("Hello "   value);
}

function pass2(){
  return (" Howdy!");
}

function receive_pass(func1, func2){
  console.log(func1("world!") func2());
}

receive_pass(pass1, pass2);
  • Related