Intermediate Algorithm Scripting - Arguments Optional

Tell us what’s happening:
Describe your issue in detail here:
When I console.log(arguments), I get two object:
1.{ ‘0’: 5 }
2.{ ‘0’: 7, ‘1’: 7 }
I do not know why the arguments[0] has changed from 5 to 7 in addTogether() function. Can you explain that to me? And how to solve this problem? Thank you so much.

   **Your code so far**
function addTogether() {
 console.log(arguments)
if(arguments.length === 1){
return function addNumTwo(num2){
  return  addTogether(arguments[0], num2)
} 
} else {
  console.log(arguments[0])
  console.log(arguments[1])
  return arguments[0] + arguments[1]
  
}
}

console.log(addTogether(5)(7));
   **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Arguments Optional

Link to the challenge:

When in doubt, write clearer log statements.

function addTogether() {
 console.log('main function', arguments)
  if(arguments.length === 1){
    console.log('if branch')
    return function addNumTwo(num2){
      console.log('curried function', arguments)
      return  addTogether(arguments[0], num2)
    } 
  } else {
    console.log('else branch')
    console.log(arguments[0])
    console.log(arguments[1])
    return arguments[0] + arguments[1]
  }
}

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

Inside that curried function, what are the arguments?

2 Likes
return function addNumTwo(num2){
  return  addTogether(arguments[0], num2)
} 

At this point where you return the addNumTwo, your arguments object no longer points to the outermost addTogether function but instead points to the arguments of the addNumTwo function.

function addTogether() {
const addTogetherArgs = arguments
if(arguments.length === 1){
return function addNumTwo(num2){
  return  addTogether(addTogetherArgs[0], num2)
}

You could store the first argument objects first and then access it inside of the addNumTwo function. This way your original arguments object is preserved.

1 Like

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