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

272
Visualizações
Whats going on here im trying to wrap my head around recursion and this return function

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

So far I understand that by me setting countArray to the function it decides to call itself until n = 0 . At that point it returns an empty array to countArray but i just don't understand what happens after that point that gives this odd outcome of the numbers being ordered, i assumed it would just push the current value of N being 0 to the array but it clearly doesn't...

Does anyone know what's going on here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

0 is not pushed to the array because of the if condition. At that point your countArray is set to [].

When using recursion interpreter needs a way to be able to understand in which order these functions have to be processed.

When your script runs first time, the interpreter creates a global execution context and pushes it to the execution stack.

Once it finishes, the engine executes the function whose execution context is at the top of the stack first. In your case n=1. It pushes it to the array, pops it from the stack then continues n=2 and so on until it reaches the last one in the stack n=5

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    console.log(n)
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

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