Reaching the Second Argument

Tell us what’s happening:

I could not understand how to reach the separated second argument that in the second parentheses even though I tried to do by the else if block. However I could not make it. I appreciate if you may help. Thanks.

Your code so far


function addTogether() {

let a = arguments[0];
let b = arguments[1];

if (typeof a !== 'number' || typeof b !== 'number') {
  return undefined;
} else if (arguments.length === 1 && typeof a === 'number') {
  return function (args2) {
    if (typeof args2 !== 'number') {
      return undefined;
    } else {
      return a + args2;
    }
  }
} else{
  return a + b;
}
}

console.log(addTogether(2)([3]));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.

Challenge: Arguments Optional

Link to the challenge:

hey brother ,
when the arguments.length === 1 then let b = arguments[1]; and typeof b !== ‘number’ might not work.
so put this let b = arguments[1]; , in else block when the arguments length is 2.
" when we are not sure the number of parameters to function it is always better to use rest parameters "

if that does not work try this below code.

function addTogether(...args) {
  for(let i=0;i<args.length;i++){
    if(typeof args[i] !== 'number')
      return undefined;
  }
  if(args.length == 2)
    return args[0]+args[1];
  else if(args.length == 1){
    var func =  (num) => {
        if(typeof num !== 'number')
          return undefined;
        return num+args[0];
    }
    return func;
  }
}

addTogether(2,3);
1 Like

You’re doing good there. I tried to understand the code this way:

Put console.log('going this way') on each conditional. And plug only one number on the function. (cause that one only seems to be the problem).

You will find out, what’s going on.


Also, I guess this is still valid and looks simple:

let [a,b] = arguments

Instead of your first two lines.

1 Like

Hey bro, firstly thanks for your nice answer,
Taking the b variable into the else if block was helpful. May you explain the reason of the problem with the variable b and the arguments.length comes from because of the first condition and second condition are colliding logically? If it is, then why?

when the arguments.length is 1 , you are trying to access arguments[1] and store it in b variable. but it returns undefined . since there is only one element.

let b = arguments[1];  // Returns  undefined

when you come to if block

typeof b !== 'number'  // returns  undefined

so
typeof a !== 'number' || typeof b !== 'number'  //  this is always true;
so it enters if block and returns undefined.   

so if you omit let b = arguments[1]; and put it in else block
when any of the numbers is not type ‘number’ it enters if block
when arguments.length is 1 it enters else if block
when arguments.length is 2 it enters else block

hope this makes it clear.

1 Like