HolyMoly - 1 year ago 78

Javascript Question

So I am going back to some of the basics and found that I am having trouble with the simplest of things. I have a callback that is throwing me an error, I suspect this is a hoisting thing, but have been googling and can't seem to find what I am looking for.

`function add (a,b){return a+b;}`

function multiply (a,b){return a*b;}

function applyFn(callback) {

return callback;

};

var f = applyFn(add);

console.log(f); //logs => function add(a,b){return a+b;}

f(3)(4); // returns => Uncaught TypeError: f(...) is not a function(…)

I know that

`var f`

`console.log(typeof f)`

`function`

EDIT:

for more clarity the applyFn was supposed to be able to use either the

`add`

`multiply`

`function add (a,b){return a+b;}`

function multiply (a,b){return a*b;}

//I needed to write this function, but nothing else

function applyFn(callback) {

return function(){};

};

var f = applyFn(add);

var x = applyFn(multiply)

f(3)(4);

x(6)(8);

Answer Source

To answer your question, you need to look at what `applyFn`

returns. It takes a function, and simply returns that function. If you assign what it returns, the variable that you assigned to is now simply a reference to the function you originally passed in. In this case, that's the function `add`

and it simply adds two numbers together. When you call `f`

, you're really calling `add`

, which means 1. it needs two arguments and 2. it's going to return the result of adding the two arguments, not another function that you can then call. If your goal is to do currying, then your function needs to return another function, so that it can be invoked:

```
function adder(num1) {
return function (num2) {
return num1 + num2;
};
}
adder(2)(3);
```

Here is what I think you're looking for:

```
function applyFn(func) {
return function (x) {
return function (y) {
return func(x, y);
};
};
}
```

This implementation of applyFn should do what you expect with `add`

and `multiply`