Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
The return statement is throwing out an undefined value for a recursive function

I am trying to solve this question->
https://www.codewars.com/kata/541c8630095125aba6000c00/train/javascript

Basically the purpose of the function is to:
16 --> 1 + 6 = 7
942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2

I am able to get the correct answer ("final sum") in my console.log but I am not able to get that value in the written statement.

function digital_root(n) {
  console.log("initial", n)
  let sum=0
  
  while(n>0){
    
    sum+= n%10
    console.log("sum",sum)
    n= Math.floor(n/10)
    console.log("num",n)
    
  }
  if(sum>10){
    digital_root(sum)
  } else{
      console.log("final sum",sum)
      return sum}
}

Here's the console.log->

initial 16
sum 6
num 1
sum 7
num 0
final sum 7
initial 195
sum 5
num 19
sum 14
num 1
sum 15
num 0
initial 15
sum 5
num 1
sum 6
num 0
final sum 6
initial 398754
sum 4
num 39875
sum 9
num 3987
sum 16
num 398
sum 24
num 39
sum 33
num 3
sum 36
num 0
initial 36
sum 6
num 3
sum 9
num 0
final sum 9

its returning undefined instead of 6 & 9 respectively.

Also a humble request is to not suggest an alternative solution but to help me fix this one. Thank you

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!