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

132
Visualizações
Recursion function in JavaScript

I have a simple recursion function that returns the sum of the first n elements of the array. I'm a little bit struggling with understanding: when the function calls itself through return return sum(arr, n-1) + arr[n-1]; what actually this sum(arr, n-1) does as it is not added to the final sum eventually and why it's not been calculated.

Here's the whole function, really appreciate any explanation.

function sum(arr, n) {
  if (n === 0) {
    return 0;
  } else if (n >= 1) {
    return sum(arr, n - 1) + arr[n - 1];
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In a recursive function, you want to start with the leaving return statement, which in this case is when the array is empty.

// if the array is empty, return the total.
if(!arr.length) return total;

If we have more items, pop the top item and add it to the total. Popping returns the last item and removes it from the array.

total += arr.pop();

Then we return the recalled function and pass it the updated parameters.

return sum(arr, total);

function sum(arr = [], total = 0) {
  if (!arr.length) return total;
  total += arr.pop();
  return sum(arr, total);
}

console.log(sum([1, 2, 3]))

about 4 years ago · Juan Pablo Isaza 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