Arguments Optional: addTogether(...) is not a function

<%= @topic_view.topic.title %>
<%= @topic_view.topic.average_rating %> <%= @topic_view.topic.posts.count { |p| !!p.custom_fields['rating'] } %>

Tell us what’s happening:

Error shows: addTogether(…) is not a function.

I make the spread array items as the parameters which I used many times before but now throws an error.

Thank guys very much for your answers.

Your code so far


function addTogether(...num) {
  if (num.length === 1) {
    if (typeof num !== 'number') {
      return undefined;
    } else {
      return num2 => typeof num2 !== 'number'? undefined: num + num2;
    }
  } else {
    for (let item of num) {
      if (typeof item !== 'number') {
        return undefined;
      }
    }
    return num.reduce((a, b) => a + b);
  }
}

console.log(addTogether(2, 3));

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional

1 Like

For the test case of addTogether(2)(3), when the addTogether function is first called with 2 as the argument, num is an array with the number 2 as its only element, so the following if statement evaluates to true and you return undefined, because when you call typeof on an array, is is definitely not equal to ‘number’.

if (typeof num !== 'number') {

Then, since you return undefined instead of a function, you get the error message you see, because you are basically making the following call:

undefined(3)

which is a problem.

1 Like

Yes I should check the type of the element rather than the array.

Thank you Randell for your answer.