Arguments Optional Array Problem

Hey guys, getting real close to the end of intermediate here, pretty happy about it, although a little exhausted from many hours of frustration with the wild language that javascript is. Here’s my latest head scratcher:

function addTogether() {
  
  var args = Array.from(arguments);
  
  if (typeof args[0] === "string" || typeof args[1] === "string") {
    return undefined;
  }
  
  if (typeof args[1] === "object") {
    return "undefined";
  }
  
  if (args.length === 2 && !isNaN(args[0]) && !isNaN(args[1])) {
    return args[0] + args[1];
  }
}

addTogether(2, [3]);

I’m trying to catch that sneaky array [3] in my second if statement and nothing seems to be able to get it to return undefined. Thing is, it falls into the condition block and returns anything but undefined, hence the quotes. Remove the quotes, and nothing is returned. Is this a bug? Or am I losing my mind here? Thanks.

1 Like

First: you know that your test case is not the same as in the assignment?


If either argument isn’t a valid number, return undefined.

Why can’t you just check if typeof args[0] and typeof args[1] is "number"?

And if you return from function without returning a value, you are returning undefined.

So your code can be reduced to this:

Click to see
function addTogether() {
  
  var args = Array.from(arguments);
  
  if (typeof args[0] !== "number" || typeof args[1] !== "number") {
    return;
  } else {
    return args[0] + args[1];
  }
}

Now you have to implement this (which is the main point of this assignment):

If only one argument is provided, then return a function that expects one argument and returns the sum.

2 Likes

Hi jenovs,

Thanks for the reply. I should of specified, I know my code isn’t optimized or succinct, and when something doesn’t work, I tend to spread out portions of my code in an attempt to make my mistake obvious. When I don’t understand a specific behavior I can’t get over it until I figure it out, and it happened again here.

I just re-wrote this entire second paragraph because I figured out what my problem is as I was replying to you. I was working on this late last night and for some reason misread the last test as (2, [3]) instead of (2)([3]), throwing me off. I definitely feel like a fool (again), and need to work on my reading comprehension/slow down before flipping out. :wink: On to advanced!

Thanks again.

Rubber duck debugging for the win!

(Seriously, it’s a thing. :slight_smile: )

1 Like