Intermediate Algorithm Scripting - Arguments Optional

Tell us what’s happening:
I’m not sure how to get this to call itself correctly, so it can update the total value when I have 2 separate arguments given to it. some guidance in the correct direction would be appreciated.

Your code so far

function addTogether() {
  let total = 0

  if ([...arguments].some(ele => !Number.isInteger(ele))){
    return undefined
  } else if (arguments.length > 1){
   return [...arguments].reduce((a,b)=> a + b)
  } else if (arguments.length == 1){
   total += arguments;
   return addTogether()
  } else{
    return total
  }
}

addTogether(2, 3);

Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Arguments Optional

Link to the challenge:

Your code is basically fine until after the condition arguments.length == 1.

Firstly, total += arguments doesn’t work because you’re trying to add together a number and an object-like-array.
Also, you don’t actually need a total variable at all.
Then, trying to return the original function like that isn’t going to work either.

At this point in the code, you should return a new function which takes one parameter, checks if it is a number and returns either undefined (if not) or the sum of that number plus the original number passed to the addTogether function. So, you’re essentially returning a value in the main function by returning a new function which itself returns a value, if that makes sense?

How to do this? You could use a Rest parameter in your original function:

function addTogether(...args)

This will put all user-supplied arguments into an args array. This would also allow you to tidy up your code by using args instead of [...arguments]. Chiefly though, it allows you to access the first user-supplied argument to addTogether as args[0] in the new function which you return after the arguments.length == 1 condition.

Finally this can be an else condition (as opposed to else if) as there’s nothing else to be done in the main function after this.

It’s tricky to get your head around but I hope that makes sense?

Thank you for your help, this cleared a lot up

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