About the closure in JS

About the closure in JS
0

#1

I am trying to finish the “Arguments Optional” challenge, my code is as below:

function addTogether() {
  if(arguments.length === 2){
    if(typeof arguments[0] !== 'number' || typeof arguments[1] !== 'number')
      return undefined;
    else
      return arguments[0] + arguments[1];
  }
  else if(arguments.length === 1){
    var c = arguments[0];
    return function(element){
       if(typeof c !== 'number' || typeof element !== 'number'){
          console.log("SSSSSSSSSSSSSSSS");
          return undefined;
       }
       else
        return element + c;
     };
  }
}

when I perform the function addTogether("http://bit.ly/IqT6zt");, the result is as below:

     function(element){
       if(typeof c !== 'number' || typeof element !== 'number'){
          console.log("SSSSSSSSSSSSSSSS");
          return undefined;
       }
       else
        return element + c;
     };

It seems that the inner function in the “addTogether” is not been performed, but as a string to be returned.

I do not know well about closure in JS, I don’t know why the inner function is not be performed.I think the result should be “undefined”.Please give me some guide.Thanks a lot!


#2

When you make the call addTogether(“http://bit.ly/IqT6zt”), your if statement above is checking for 2 arguments. This url passed into the function is only one argument, so your else if check if there is one argument and there is, so the actual function is returned instead of the value undefined.

Your logic needs to recognize if any of the arguments passed in are not valid numbers, then you should return undefined.

HINT: You only need to add one extra condition to the following else if and then also and one final else block of code.

else if(arguments.length === 1 && ???){

#3

Thanks for your reply!
when I make the call addTogether(“http://bit.ly/IqT6zt”), the else if check statement will run, but I still do not know why the inner anonymous function does not run? I think this is a closure in JS.


#4

Because you wrote the following, you are returning the actual function and not executing the function. To execute a function, it would be followed ().

return function(element){

#5

I solved the problem with your help, thanks a lot!