I’m trying to understand how those functions with 2 sets of parenthesis work with closure.
Beside getting into the closure, i would like to understand why I can’t get just the value of the first parenthesis? it always gives me an error message after, like it can’t read what is after. Which is fine because I just want the value from the first parenthesis!
Here is my code:
function addTogether() {
console.log(arguments[0]);
}
addTogether(2)(3);
I am expecting 2 as an answer.
Same when I’m trying to reuse some part of the basic answer of the challenge to test if arguments[0] is a number or not.
function addTogether() {
var c = arguments[0];
if (typeof c == number){
console.log('yes')
}
else{
console.log('no')
}
}
addTogether(2)(3);
All I get is an error. So I wonder how the solution for the challenge works if I can’t even get the number value in the first argument.
Yes it does, but when trying to check if number or not, the error is still passed right? that’s why I can’t get a yes or no answer? or it is for something different?
In the test case of addTogether(2)(3), the first part addTogether(2) should take the value 2 and return a function which will add the 2 to an argument of the returned function, so when the (3) is encountered, it is just the execution of the function which is returned with an argument which has a value of 3.
So i can’t just take the number of the first arguments without having the error after? How can I store the first argument in a variable without having the error?
i’m sorry fr all those questions, but it is bugging me
The function addTogether is first called with the value 2 as it’s argument (the addTogether(2) part). The second part (3) is not part of the first function call. Instead it is a chained function call which needs a function to be returned from the original addTogether(2) call for it to properly execute. See below for the basic logic the addTogether function should have. You will still need to check that any and all values passed to addTogether are numbers, but I will leave you to figure that part out.
function addTogether(firstNumber) {
function functionThatReturnsTheSumOfFirstNumberandSecondNumber (secondNumber) {
// return the sum of firstNumber and secondNumber here
}
return functionThatReturnsTheSumOfFirstNumberandSecondNumber;
/*
The line above returns the above function so that it can called with
the value 3 as it's argument which is the (3) part in the chained call of
the test case below.
*/
}
addTogether(2)(3); // should return 5
Ok thank you guys, I think i got a quick understanding of the whole concept.
I’m still struggling to understand why I can’t just receive the number as an answer without the following error message when trying independently of the addTogether function.