My solution works but I am not sure why other solutions did not

Tell us what’s happening:
As stated in the title, the code at the very bottom under “Your code so far” works correctly but it’s resulted in me being confused. My main confusion lies with the if-statements that check the typeof for ‘arg1’ and ‘arg2’.
When I had the condition combined to look like:

if(typeof(arg1) != "number" || typeof(arg2) != "number"){
return undefined;
}

or if I had the conditions one after the other like:

function addTogether() {
  let [arg1, arg2] = arguments;
  if(typeof(arg1) != "number"){
    return undefined;
  }

 else if(typeof(arg2) !== "number"){
    return undefined;
  }
  
  else if(arguments.length == 1){
    function addArg2 (arg2) {
      if (typeof(arg2) != "number"){
        return undefined
      } else{
        return arg1 + arg2
      }
    } return addArg2
  }
  
  else{
    return arg1 + arg2;
  }
}

console.log(addTogether(5)(7));

I would receive an error message stating that addTogether() was not a function. If anyone could provide some clarification, that would be amazing, and sorry in advance if this is a bit confusing to read or follow.
Your code so far

function addTogether() {
  let [arg1, arg2] = arguments;
  if(typeof(arg1) != "number"){
    return undefined;
  }
  
  else if(arguments.length == 1){
    function addArg2 (arg2) {
      if (typeof(arg2) != "number"){
        return undefined
      } else{
        return arg1 + arg2
      }
    } return addArg2
  }

  else if(typeof(arg2) !== "number"){
    return undefined;
  }
  
  else{
    return arg1 + arg2;
  }
}

console.log(addTogether(5)(7));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Arguments Optional

Link to the challenge:

Here you are stopping prematurely and never handling the case where only one argument is provided. Whenever only argument is provided, the type of the second argument is automatically undefined

1 Like

Ahhh alright that makes sense. That never even entered my mind.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.