I’m learning the basics of JavaScript and am trying to write a recursive function to add together a group of integers. For example, the function argument would be 1234
and the result should be 10
. Here’s what I have so far…
function sumDigits(numbersStr) { var numToString = numbersStr.toString() var numArr = numToString.split('').map(Number); var sum = 0; // base case if (numArr.length === 0) { return sum } // recursive case else { var popped = numArr.pop(); sum+=popped; return sumDigits(numArr); } }
But I get an infinite loop whenever I run this (my tab crashes). If I’m popping the last element of an array, adding it to the sum
variable, then calling the function again on the shortened array, then why do I get an infinite loop? Many thanks!
Advertisement
Answer
The problem in your code is that sumDigits expects to get a number, but in the recursion you pass an array of numbers to it.