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

99
Visualizações
return statement that returns nothing in recursion

I found this code about recursion online

function countDownRecursive(n) {
  if (n <= 0) {
    console.log('Hooray')
    return
  }

  console.log(n)
  countDownRecursive(n - 1)
}

I am really confused about this code, why does it console.log("Hooray") and then return nothing? Can you explain it to me? Thank you so much.

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

0

you returned a null value, the function output type is void. try this

if (n <= 0) {
    console.log('Hooray')
    return n
  }
about 4 years ago · Juan Pablo Isaza Relatório

0

return in this context means you don't want to continue running the function (similar to break in iterations).

The above recursive function's logic can be converted to this below while logic.

let n = 3;
//iterate until found the while break
while (true) {
  //the condition to stop
  if (n <= 0) {
    console.log('Hooray');
    break; //stop `while`
  }
  console.log(n)
  n = n - 1;
}

about 4 years ago · Juan Pablo Isaza Relatório

0

why does it console.log("Hooray")

Because the function is recursive and when you start with let's say n=1 the function will not print "Hooray" immediately, because the condition:

if (n <= 0)

does not apply i.e. is false.

By the time we reach the recursion:

countDownRecursive(n - 1)

We call the function again with n=0 due to n - 1, the if-statement will evaluate to true and therefore print "Hooray".

and then return nothing

It does not actually return "nothing", even though the return type is void, it returns undefined, which is the default behavior for return you could also write return undefined instead.

When you use return, it will basically terminate or return from the current function. It will jump back into the scope where you did call the function initially.

Hope that clears it up for you.

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