Reputation:
So I'm following Douglas Crockfords lectures on JS. One of his exercises is "write a function that takes one argument, and returns a function that returns the argument". The next question is "write a function that adds from two invocations".
I got the answer to both, what I don't get is why one doesn't post to the console and the other does. Here's what I mean. This is my answer to the first question:
function retFunc(x){
return function(){
return x;
};
}
console.log(retFunc(4));
This posts the following to the console:
function(){
return x;
}
However if I change it to this, it'll post 4 to the console (which is what I wanted):
var idf = retFunc(4);
console.log(idf());
Now this is my answer to the second question:
function addf(x){
return function(y){
return x+y;
};
}
console.log(addf(3)(4));
And this works, it spits out 7 to the console. My question is, why does the first one not work? And this one does? Both are functions that return another function, that finally returns a value.
Upvotes: 0
Views: 1299
Reputation: 6920
Instead of console.log(retFunc(4)); try console.log(retFunc(4)()); You have two nested functions. so you should call inner fucntion too.
Upvotes: 0
Reputation: 12670
The difference is that in your first case you are not calling the returned function, but in the second one you are
console.log(retFunc(4));
var idf = retFunc(4);
console.log(idf()); // <-- note the parentheses.
Upvotes: 1
Reputation: 230521
why does the first one not work?
First one does work, exactly as it should. You call a function which returns you a function, but you don't call that second function. You print it instead.
Upvotes: 3