-2

When the function is passed with a parameter an error is returned that a is not a function while without parameter it executes and gives output 3

function one(d) {
  return 1;
}

function two() {
  return 2;
}

function invokeAdd(a, b) {
  return a() + b();
}
console.log(invokeAdd(one(8), two));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 2
    `one` returns a `number` not a `function` - use TypeScript – Dai Nov 20 '22 at 04:44
  • You have to use `callback` function for the first argument in the `invokeAdd` like this -> `invokeAdd(()=>one(4) , two`. – Ankit Nov 20 '22 at 04:52

5 Answers5

1

As Dai said, you are using the result of the function as the parameter, making the parameter a number rather than a function. To return the function itself, use the arrow operator to make it invoke it.

invokeAdd(() => one(8), two))

MrDiamond
  • 958
  • 3
  • 17
1

Passing functions to other functions

Let's take the following as an example:

function invokeAdd(param) {
  return param;
}

Try logging out a function like this.

function invokeAdd(param) {
  return param; 
}

console.log(invokeAdd)

You will notice that in the console it will show you the function definition since that is what the invokeAdd variable is storing.

Now let's try logging the function with arguments.

function invokeAdd(param) {
  return param;
}
console.log(invokeAdd("test"))

You'll notice you'll get the return value for the function that is the argument we passed.

So when you try console.log(invokeAdd(one(8), two)); Your first parameter is essentially passing the result of one(8) not the actual function.

M. G.
  • 343
  • 1
  • 7
0

When you run one(8), you are executing a function not passing it. So what you are passing to invokeAdd is the result of one(8).

Try doing it this way:

function one(d) {
    return 1;
}
function two() {
    return 2;
}
function invokeAdd(a, b) {
    return a() + b();
}
console.log(invokeAdd(() => one(8), two));
0
function invokeAdd(a, b) {
return a() + b();
}

This function two parameters which should be functions whereas what you are doing is giving a value and a function instead of two functions. To get what you want do this

console.log(invokeAdd(()=>one(8), two));
Mohammed Shahed
  • 840
  • 2
  • 15
0

since you have executed the function "one" while passing the parameters itself. Hence this is the issue. Below is the explanation for same.

You have passed 2 functions a and b as parameters to the function "invokeAdd".

When function "invokeAdd" executes and on call stack it expects "a" to be function and executes when we use the parentheses("()").

Now since while invoking the function "invokeAdd" we have executed the function and return value after execution is the actual value which is "1" in this particular case.

While for "b" we have passed the function reference and it executes when sum operator is triggered.

Hope this helps

Hemant Kumar
  • 186
  • 6