Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript recursive function is returning strange value

Here is my code, why it is returning 13 in place of 4:

const superNumber = (n) => {
  let nums = n.toString().split('').map(Number);
  let sum = parseInt(nums.reduce((x, y)=> x + y));
  console.log('Nums: ',nums, 'Sum: ', sum);
  if(sum > 9) {
     superNumber(sum);
  }
   return sum;
}

let result = superNumber(148);
console.log('Ans: ', result);

Here is the console log:

  • Nums: [1, 4, 8] Sum: 13
  • Nums: [1, 3] Sum: 4 // Calculated sum
    correctly but returning the previous value
  • Ans: 13

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You forgot a return there

if (sum > 9) 
    return superNumber(sum); // Here you forgot to return
const superNumber = (n) => {
  let nums = n.toString().split('').map(Number);
  let sum = parseInt(nums.reduce((x, y) => x + y));
  console.log('Nums:', nums.toString(), ' Sum:', sum);
  if (sum > 9) {
    return superNumber(sum);
  }
  return sum;
}

let result = superNumber(148);
console.log('Ans: ', result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading