Reputation: 41
In the following recursive function, I expect the function to return "arrived"
at the end but instead, it returns undefined
. Isn't that when the excution goes in the if
block the code should return? Appreciate your comments on this.
function myFun(i){
if(i===0){return ('arrived');}
i = i - 1;
myFun(i);
}
If I change the code as follows then it'll return "arrived"
but still don't know why the above doesn't return "arrived"
.
function myFun(i){
if(i===0){return ('arrived');}
i = i - 1;
return myFun(i);
}
Upvotes: 3
Views: 216
Reputation: 135197
Recursion is a functional heritage and so writing your program in a functional style will yield the best results.
This means avoiding things like
for
, if
, switch
, etc that do not return a valuei = 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
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
Upvotes: 1
Reputation: 24137
The first function does not return a value because all code paths must return a value. And after the first line, there is no return
statement. It only returns a value when called with 0
as parameter.
Upvotes: 7