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

195
Visualizações
JS, Recursion, Function Stack Example, Hard to Understand

Below is an example from MDN Function scope. I can not understand how the end: 0 and the rest of end: are printed. I was expecting that the console.log("end: " + i); will never be reached.

function foo(i) {
  if (i < 0) return;
  console.log("begin: " + i);
  foo(i - 1);
  console.log("end: " + i);
}
foo(3);

Output:

begin: 3
begin: 2
begin: 1
begin: 0
end: 0
end: 1
end: 2
end: 3
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If I were to write:

console.log("begin");
my_custom_function(1);
console.log("end")

Then console.log will log begin, then my_custom_function will be called, and when my_custom_function has finished it will pick up where it left off and console.log will log end.

It's exactly the same.

When foo has finished, it will return to the calling function (which happens to also be foo) and continue where it left off.

about 4 years ago · Juan Pablo Isaza Relatório

0

The trick to all recursion is the exit condition. Without it the function will run forever or the system runs out of memory. The exit condition for foo is if (i < 0) return;. Now because javascript is, in this case at least, run synchronously, it will finish whatever it is doing before moving on to the next line of code.

The function calls itself with foo(i - 1); which will in turn call itself and so on until the exit condition is met. It is therefore vital that the exit condition is placed before the recursive call.

To make this easier to understand, consider the value of i for each successive call:

foo(3)
  foo(2)
    foo(1)
      foo(0) // exit condition is met, ending the recursion
      print end 0
    print end 1
  print end 2
print end 3

about 4 years ago · Juan Pablo Isaza Relatório

0

Think about it in blocks. Below I added each step showing the actual i values and indenting it on each recursion. You can see that after the recursion is done, then it will finish the function call on each of the previous blocks.

foo(3) {
    if (3 < 0) return;
    console.log("begin: " + 3);
    foo(3-1) {
        if (2 < 0) return;
        console.log("begin: " + 2);
        foo(2-1) {
            if (1 < 0) return;
            console.log("begin: " + 1);
            foo(1-1) {
                if (0 < 0) return;
                console.log("begin: " + 0);
                foo(0-1){
                    if (-1 < 0) return; // Exit recursion
                }
                console.log("end: " + 0);
            }
            console.log("end: " + 1);
        }
        console.log("end: " + 2);
    }
    console.log("end: " + 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