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

125
Views
Return returns undefined but console returns value

Algorithm for the recursive sum of all the digits in a number. Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6.

Could someone tell me why there is a correct sum in the console when i print it by console.log but when i want to return there is undefined?

let sum = 0;

const sumOfDigits = (num) => {
  let number = num.toString();

  if (number.length > 1) {
    sum = 0;
    [...number].forEach((digit) => {
      sum += Number(digit);
    });
    sumOfDigits(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(sumOfDigits(942));
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You dont return the value for all the calls

Change sumOfDigits(sum); to return sumOfDigits(sum); like below

let sum = 0;

const sumOfDigits = (num) => {
  let number = num.toString();

  if (number.length > 1) {
    sum = 0;
    [...number].forEach((digit) => {
      sum += Number(digit);
    });
    return sumOfDigits(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(sumOfDigits(942));

about 4 years ago · Santiago Trujillo Report
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!