Intermediate Algorithm - Arguments Optional. - Need an explanation [SPOILERS]

Intermediate Algorithm - Arguments Optional. - Need an explanation [SPOILERS]
0

#1

Hello,

I recently completed the Arguments Optional problem. However, I am not 100% sure why it works and I was hoping someone could explain it to me.

My solution:

`````` function addTogether(a,b) {
if (typeof a ==='number' && typeof b === 'number') {
return a + b;
}
else if (typeof a ==='number' && typeof b ==='undefined') {
return function(b) {
if (typeof b === 'object') {
return undefined;
} else {
return a + b;
}
};
}
}
``````

If you look at this specific part below. I am checking typeof b for ‘undefined’ yet for some reason after I check it and it is undefined, if I check it again in the inner if statement, it is suddenly an object in some cases. Why would it randomly change from undefined to object?

``````else if (typeof a ==='number' && typeof b ==='undefined') {
return function(b) {
if (typeof b === 'object') {
return undefined;
} else {
return a + b;
}
};``````

#2

Notice what you’re returning.

``````return function(b) {
if (typeof b === 'object') {
return undefined;
} else {
return a + b;
}
}
``````

If `a` is a number and `b` isn’t, the function returns another function and not another value. This function gets called later. Here’s how the program works:

``````var sum = addTogether(10,7); // 17
var nextStep = addTogether(15); // Returns a function with '15' as the first value
var finalStep = nextStep(8); // Returns 23 (15 + 8)
``````

So, there needs to be another check for `b` to make sure that it’s a number when that returned function gets called.