Undefined for return value but returning a valid value

I can see that the return value that I plan to return is a valid value. I print it out just before the return. I think this is closure related since it is happening when a function is being returned and that function is then called. I have given the code below along with the console logging messages for two invocations.

CODE:

function addTogether() {
const [a, b] = arguments;
console.log(`a: ${a}  b: ${b}`);

if (typeof a !== 'number') {
  return undefined;
  }
if (b !== undefined){
  if (typeof b !== 'number'){
    return undefined;
  } else{
    let sum = a+b;
    console.log("sum being returned =", sum)
    return sum;
    }
}
return ((b)=>{
addTogether(a,b);
});
}
console.log("returnVal =", addTogether(2,5));
console.log("returnVal =", addTogether(5)(7));

CONSOLE LOG OUTPUT:

a: 2  b: 5
sum being returned = 7
returnVal = 7
a: 5  b: undefined
a: 5  b: 7
sum being returned = 12
returnVal = undefined
  **Your browser information:**

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

Challenge: Arguments Optional

Link to the challenge:

Well, I figured out how to fix it but I’m not sure I’m fully grasping it yet.
I fixed it by replacing:
return ((b)=>{
addTogether(a,b);
});
with:
return ((b) => addTogether(a,b));

I’d review the documentation about arrow functions

Yes, I reviewed it after i wrote this and know the difference just trying to get my head around why the expression needs to be returned and not the function.

You need to return a function. But you need to return a function that has an actual return value.

This returns a function that has no return value

If you are using a function body with {} for an arrow function, you need an explicit return statement.

1 Like

Oh, yeah. Right. Thanks. Damn, I figured this out once quite a while ago and for whatever reason it vanished from my brain. Obvious now that you reminded me again. I kept thinking that the function called within my function had the return so I was covered but it returns back to the function I passed that is invoking it so that needs a return (unless I pass just the expression and not the function). Thanks a ton for pointing this out to me again. All makes sense again now.

1 Like

Cool! Learning and re-learning is what it’s all about!

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