Link to challenge: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional/
- When adding || typeof(y) !== ‘number’ in first else if, only 3 out of 5 tests pass
- When removing || typeof(y) !==‘number’, all tests pass except for one: addTogether(2, “3”)
Code so far:
function addTogether(x,y) {
if (arguments.length > 1) {
return x + y;
} else if ( typeof x !== 'number') {
return undefined;
}
return function (y) {
if ( typeof(y) !== 'number' ) {
return undefined;
}
return x + y;
};
}
addTogether(2,3);
Let’s examine this logic here:
if (arguments.length > 1) {
return x + y;
} else if ( typeof x !== 'number') {
return undefined;
}
If there are more than one argument, it just going to try and sum them and return that. It will never hit that else if
unless there is only one param. Is that what you want? I think you might think about the order here.
Additionally, the instructions say:
If either argument isn’t a valid number, return undefined.
It doesn’t say, "If the first argument is invalid…* The problem for which you are failing is one where the first is valid, but it’s the second one that is the problem. Don’t just look at it and say, “Oh, it’s failing.” Try to understand why.
Thank you Kevin. I think I get the first part of your response. The first else if won’t return properly in its current position. I’ll rewrite it so this is first and check both x and y, which do work when I try it. Other parts of the tests fail when it’s rewritten. I’ll take a look closer at what may be causing and keep what you said in mind. thx.
Looking a little deeper, the logic is a little more complex than I thought. I was able to get it to work, but it wasn’t as simple as I was first imagining. I’d recommend trying to write the logic out on paper, in pseudo code, just figure out what the logic should be and then worry about the code.
Let us know if you get stuck.
1 Like
Ok. I finally got it. I was not considering ordering into my logic. After playing around with that a bit I realized the single parameter should get checked first, and so on. The code stayed more or less the same.
1 Like