Treadstone
Treadstone

Reputation: 39

Pass a function with parameter as an argument to another function in JavaScript

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

Upvotes: 0

Views: 67

Answers (2)

Behemoth
Behemoth

Reputation: 9360

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);

Upvotes: 2

mohamed ouf
mohamed ouf

Reputation: 36

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);

Upvotes: 2

Related Questions