Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda