Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda