Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda