Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Alex Flores
7,864 PointsJavaScript High-end functions - question
I'm reading Eloquent JavaScript, which I highly recommend to anyone interested in learning JavaScript. Anyways, I'm reading the chapter on High-end functions and I've come across this one, that kinda boggles my mind. I was hoping someone could try to explain to me the logic behind it.
<script>
function noisy(f) {
return function(arg) {
console.log("calling with", arg);
var val = f(arg);
console.log("called with", arg, "- got", val);
return val;
};
}
noisy(Boolean)(0);
// → calling with 0
// → called with 0 - got false
</script>
Link to the book - http://eloquentjavascript.net/05_higher_order.html
Now, I can accept that it passes on an argument by using a new set of parenthesis, but I was hoping someone could explain why it works this way? What is this telling the interpreter?
I appreciate any help I can get!
2 Answers
Brian Steele
23,060 Pointssorry, yes it's the second function invoking with a 0 passed to it. The parenthesis are the invoking action of the function. Good luck!
Alex Flores
7,864 PointsWhat are 0-second set of parents? I'm assuming you mean the second set of parenthesis -"(0)"-? I tried googling it, but nothing comes up for second set of parents. Also, it won't allow me to give you best answer for some reason.
Thanks for your help
Brian Steele
23,060 PointsBrian Steele
23,060 PointsCalling the noisy function simply returns the anonymous function, which is then called with 0-second set of parents-as the argument. The anonymous function still has access to the argument passed to noisy "f" when it runs (closure).
The first console statement prints the anonymous function argument, 0. Then 'val' is a Boolean object called with 0, which is false, setting val to false. Finally you see the second console statement and the return value below.