+ 2

Why don't I need to write parenthesis on this function?

I consider myself "below-intermediate-above-novice" JS programmer, and I'm sure there must be some concept that I am forgetting… In the 10th line of this program, why don't I need to write parenthesis on this function? If I put them, i get TypeError saying the whole addTogether() is not a function. I don't understand. Thanks in advance for your help https://code.sololearn.com/cJLRNT7xb4iB/?ref=app

27th Mar 2021, 9:20 PM
Darío Estevanez
Darío Estevanez - avatar
7 Respostas
+ 5
Good question Darío Estevanez If you look closely at the way addTogether() is called, you will see that it's called with 5 as an argument, but there's also a 7 in parentheses. This is another function call, but it's not addTogether() that's being called with 7. What's being called is the return value of calling addTogether(5). That means addTogether(5) must return a function; otherwise, nothing can be called immediately afterwards. That function addTogether() returns is the addNum function on line 10. If you add parentheses to line 10, you aren't returning a function because the addNum function itself doesn't return a function.
27th Mar 2021, 11:11 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 2
Martin Taylor sorry for your brain 😅 I know this is kind of bad written code but I forgot to mention that I'm testing a technique i saw in FreeCodeCamp courses called "Currying a function" (well, i put it on the tags but seems not enough 😅)
27th Mar 2021, 11:10 PM
Darío Estevanez
Darío Estevanez - avatar
+ 2
Darío Estevanez I've commented the code. Hope this helps you understand it. I'm glad you asked this because currying and closures are 2 fairly advanced concepts but they're important to learn if you want to go beyond the fundamentals of JavaScript, even if you don't end up using them much. Here's the commented code...
27th Mar 2021, 11:28 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
0
function addTogether() { // addTogether is given one argument: 5 if (arguments.length === 2) { /* the if condition isn't hit because the arguments.length is 1*/ let a = arguments[0] let b = arguments[1] } else if (arguments.length === 1) { //the else condition is hit let a = arguments[0] // a is now 5 function addNum(b) { /* the addNum() function knows about a - this is called a closure by the way - but it also cares about its own parameter which is b...when addNum() is called, it'll return the sum of 5 + b */ return a + b } /* now addTogether() finishes by returning the addNum(), and that can be called because it's the addNum() function itself that's being returned, not the result of calling addNum()...we know that addNum() will be called with 5 once addTogether() finishes, meaning the result is 7 + 5 = 12
27th Mar 2021, 11:32 PM
CamelBeatsSnake
CamelBeatsSnake - avatar