0

I wrote this sum function to get used to writing recursive function.

I thought it would work when I finish writing but the final summed value becomes undefined.

There is no async part in this function but the returned value of this function becomes undefined, which I don't understand why...

What am I doing wrong?

Could anyone please tell me how to fix this problem?

Thanks!!

My code

function sum() {

    var numbers = [...arguments];

    if (numbers.length === 0) {
        return 0;
    }

    if (numbers.length === 1) {

        // it shows 15 here!!
        console.log(numbers[0]) 

        // But it returns undefined... Why!?
        return numbers[0]; 

    }

    var summedValue = numbers[0] + numbers[1];
    var restNumbers = numbers.slice(2);

    sum(summedValue, ...restNumbers)

}


console.log(sum(1, 2, 3, 4, 5)) //undefined
shu
  • 234
  • 4
  • 15
  • As an alternative, you can use `function sum(...nums) { return nums.reduce((a, c) => a + c, 0); }` – Tushar Apr 06 '18 at 06:07
  • yeah! it's way shorter that way ;) – shu Apr 06 '18 at 06:08
  • why use `apply`? you could use the spread syntax `...`, because you use ES6 with `Array.from`. – Nina Scholz Apr 06 '18 at 06:10
  • For more shorter ways, check this https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers – gurvinder372 Apr 06 '18 at 06:11
  • @Nina Scholz spread syntax does not work in my editor somehow althouth Array.from do. I use code runner when writing a small script for fun and use web storm for a serious thing. – shu Apr 06 '18 at 06:14
  • @Nina Scholz oh no my mistake. what I can't use in my editor is rest parameters and destructuring not spread operator. I changed it. sum(summedValue, ...restNumbers) – shu Apr 06 '18 at 06:16

1 Answers1

1

return numbers[0]; doesn't return undefined, it returns correct value (15 in your case).

However, your recursive function doesn't return anything to the console.log, make it

return sum.apply(null, [summedValue].concat(restNumbers))

Demo

function sum() {

  var numbers = Array.from(arguments);

  if (numbers.length === 0) {
    return 0;
  }

  if (numbers.length === 1) {

    // it shows 15 here!!
    console.log(numbers)

    // But it returns undefined... Why!?
    return numbers[0];

  }

  var summedValue = numbers[0] + numbers[1];
  var restNumbers = numbers.slice(2);

  return sum.apply(null, [summedValue].concat(restNumbers))

}


console.log(sum(1, 2, 3, 4, 5)) //undefined
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • oh...!!!! ok... Thank you so much for spotting this. I could not find it by my self without help. – shu Apr 06 '18 at 06:07