This question has already been answered:
- reduce to digital_root 1 answer
Hello! Learning javascript. Got such a problem: Given a number. It is necessary to add its numbers until the amount becomes equal to the single-digit number (9 or less). Solve using recursion.
Decided as follows:
var newSum = 0; function sumNum(num) { var sum = 0; var numArr = String(num).split(''); for(var i = 0; i < numArr.length; i++) { sum += Number(numArr[i]) } newSum = sum; if(sum > 9) { num = sum; sumNum(num); } return newSum; } alert(sumNum(34567)); Question: why the function, until you declare the variable newSum in the global scope, yields the penultimate value of newSum, i.e. two-digit number (in my example 25). Without this add. variable could not solve at all.
PS Probably, the problem was solved not at all as it should, but there was no ready solution. If there are other, more correct solutions, please show. I will be very grateful.
Duplicate question did not want to. Looking for similar, just not found.