0

I'm trying to resolve some FCC tuts. The function should be very simple, a sum function for args as an array, using the rest operator. However I don't get why my answer doesn't work, here is the code with some parameters:

function sum(...args) {
  if (args == []) {
    return 0
  } else {
    let sum = 0;
    for (let i of args) {
      sum = sum + args[i];
      i++;
    }
    return sum;
  };
};

// Using 0, 1, 2 as inputs, 3 is expected to return... and it does!
sum(0, 1, 2);

// However, if the args do not start with 0, it returns NaN
sum(1, 2);
  • 3
    [`args == []` will never be true](https://stackoverflow.com/q/30820611/1048572). (Luckily, the entire `if`/`else` is unnecessary, after looping over an empty array the code will just return `0` anyway) – Bergi Oct 22 '22 at 18:31
  • 3
    You're using `args[i]`, but [in `for (let i of args)`, `i` is an element of the array](https://stackoverflow.com/q/29285897/1048572). Just do `sum = sum + i;` instead – Bergi Oct 22 '22 at 18:32
  • You can't compare objects with comparison operators. Why not just `if (!args.length) { ... }`? – code Oct 22 '22 at 18:39
  • You know, if you're just trying to get the job done, why not something like: `const sum = (...args) => args.reduce((a, b) => a + b, 0);`. – code Oct 22 '22 at 18:40

2 Answers2

0

Change this:

    for (let i of args) {
      sum = sum + args[i];

To this:

    for (let i of args) {
      sum = sum + i;

Or to this:

    for (let i = 0; i < args.length; i++) {
      sum = sum + args[i];
0

I came up with a solution for your problem.

for(let i of args){
  // i is = the value ex: 12
  sum += i;
}

But instead of that code you can use a more simplified one like this.

function sum(...nums) {
  return nums.reduce((total, num) => {
    return (total += num);
  }, 0);
}