This question has already been answered:

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.

Reported as a duplicate at Grundy. javascript Apr 12 '18 at 17:48 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Did you use 'use strict'? - Silento
  • No, did not use. - cavy
  • A better solution is to do without recursion and loops altogether. :) - Yaant pm
  • “It’s necessary to add its numbers until the sum is equal to the single-digit number (9 or less)” - this excludes recursion: this condition will be fulfilled on the first iteration: D - yar85

2 answers 2

Because you do not use the return value of a sumNum call:

 if (sum > 9) { num = sum; sumNum(num); // !!! } 

 function sumNum(num) { var sum = 0; var numArr = num.toString().split(''); for (var i = 0; i < numArr.length; i++) { sum += +numArr[i]; } if (sum > 9) { sum = sumNum(sum); } return sum; } console.log(sumNum(34567)); 

  • And how to do it right? - cavy
  • one
    All right For recursion, you need to write sum = sumNum (sum); not what you had. Or write if (sum> 9) {return sumNum (sum);} else {return sum;} - coder675

In order of perversion:

 function sumNum(num) { return (num + '').length < 2 ? num : sumNum( (num + '') .split('') .map(d => +d) .filter(d => Number.isInteger(d)) .reduce((s, i) => s + i) ) } console.log([0, 1, -1, 8, 9, 10, 99, 123456, -654321].map(num => sumNum(num)).toString()); console.log(sumNum(Math.PI)); // ;) 

  • Thank you all very much. Very helpful. - cavy