Home > Software engineering >  What's the difference between returning inside a recursive function and having no return statem
What's the difference between returning inside a recursive function and having no return statem

Time:06-21

This code

def ok():
    ok()

gives me a RecursionError, but this code

def ok():
    return ok()

does not. Can someone explain why putting return there makes the function end, because even though I'm returning inside the first function, I'm still calling the same function again

CodePudding user response:

When a function does not return a value, it depends on a side effect. This is true for any function.

function stairs(n) {
  if (n > 0) {
    stairs(n - 1)
    console.log("*".repeat(n)) // print side effect
  }
}

stairs(5) // no returned value

When a function returns a value, the value can be used however the caller should decide -

function stairs(n) {
  if (n > 0) {
    return stairs(n - 1)   "\n"   "*".repeat(n) // returned value
  }
  else {
    return "" // returned value
  }
}

console.log(stairs(5)) // print returned value from stairs

  • Related