Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!