Arguments Optional Challenge

I was trying to do the challenge with this code

function addTogether(...args) {
  if(args.some(x => typeof(x) !== 'number')){
    return undefined;
  } 

  if (args[1] === undefined) {
    return (args[1]) => addTogether(args[0], args[1]);
    }
  return args[0] + args[1];
}

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

Which did not work. After checking the solution I saw that this works

function addTogether(...args) {
  const [first, second] = [...args];
  if(args.some(x => typeof(x) !== 'number')){
    return undefined;
  } 

  if (second === undefined) {
    return (second) => addTogether(first, second);
    }
  return first + second;
}

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

Why cant I pass args[1] as an argument to the second function ?

Thanks

Problem isn’t as much in passing the argument, but in argument naming. That part is returning new function.

return (args[1]) => addTogether(args[0], args[1]);

Taking out just the function definition and writing it in a longer syntax, it would look like:

function(args[1]) {
  return addTogether(args[0], args[1])
}

What would make the whole args[1] the variable name, and what is cause of the syntax error.

1 Like

Thanks for the answer… but how do I know which function definition to use. When should I use the longer syntax ?

Is there a general rule?

I don’t think there’s any specific rule regarding that. The longer syntax example was to show better what is happening here. That it is not really passing args[1] to the function, but defining new function - which would expect to use that name as variable name.

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