Recursion is a functional heritage and so writing your program in a functional style will yield the best results.
This means avoiding things like
- imperative style statements
for, if, switch, etc that do not return a value
- mutation or variable reassignments like
i = i + 1
const myFun = i =>
i === 0
? "arrived"
: myFun (i - 1)
console.log (myFun (10))
// "arrived"
Notice expressions, unlike statements, evaluate to a value. We made the following changes
function statement function myFun (i) { ... } replaced with a function expression myFun (i) => ...
if statement replaced with ternary expression, eg condition ? ifTrue : ifFalse
- variable assignment statement
i = i - 1; myFun(i) replaced with expression myFun(i - 1)
Note, the return statement itself is a side effect and has little use in a functional JavaScript program.
Going along with the other answer here, all code paths must return a value! An advantage to writing your program in a functional style means you can't write a function that doesn't return a value, nor can you write a conditional with only one branch.
TL;DR: use functional style and your problem automatically vanishes
foo, which does nothing but call a functionbar, which returns a value"BAR", would you expectfooto return the result of the call tobariffoodidn't have areturnstatement?function foo() { bar() } function bar() { return "bar" } foo();A recursive function is no different.