Arguments Optional | help

Hi friends, Please help me in this challange. My code is passing all the tests except one addTogether(2)([3]);.
It returns 23, below is my code, please help me to figure out what is the problem.

Your code so far

  
  function sum(x){
    return function(y){
      return x + y;
    };
  }  
  
  function isNumber(num){
    if(typeof num ==='number'){
      console.log("Number : " + num);
      return num;
    }else
      console.log("undefined : " + num);
      return undefined;
  }
  
  if(arguments.length > 1){
    var num1 = isNumber(arguments[0]);
    var num2 = isNumber(arguments[1]);
    console.log(num2);
    if(num1 === undefined || num2 === undefined){
      return undefined;
    }else{
      return num1 + num2;
    }
  }else{
    var num3 = isNumber(arguments[0]);
    if(arguments.length === 1){
      if(num3 === undefined){
        return undefined;
      }
      return sum(arguments[0]);
    }
  }
}
// addTogether(2,3);
// addTogether("http://bit.ly/IqT6zt");
addTogether(2)([3]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/arguments-optional

The issue is because of the following function that is returned in your last else{} block:

 function sum(x){
    return function(y){
      return x + y;
    };
  }  

The function doesn’t check whether y is a number or not, so it will just return x + y even if y isn’t a number—in the case you mentioned, 2 + [3], JavaScript coerces both values into a string and therefore "23" is returned.

I hope that helps!

2 Likes

thank you honmanyau, this helped to finish this challenge. I missed that part as I thought I’m checking it in the main function below where I really didn’t check ‘y’ if its number or not. Thanks for your help, I really appreciate it.
regards,
Sachin Gairola