Reputation: 79
I'm expecting the value of 'success' but i'm getting undefined. Don't understand why.
var recursion = function(n) {
if (n == 0) {
console.log('yup');
return 'success';
}
console.log(n)
recursion(n - 1);
}
var x = recursion(10);
console.log(x);
Upvotes: 0
Views: 68
Reputation: 12637
As already mentioned, you need to return recursion(n - 1);
Interesting... Thats hard to wrap my head around. When I return the function I'm expecting the function to break return a value not execute again...
But in the case of n !== 0
your function doesn't return anything.
A recursion is just a plain function call, nothing special. It's not like break
ing a loop. The return
statement doesn't flush the result through the whole call stack, just because the function called itself. It returns only to its direct caller. And in you case, the topmost function call recursion(10)
is one that doesn't return anything, therefore undefined
.
Upvotes: 0
Reputation: 115222
Missing return statement in your code when if condition is not satisfied.
var recursion = function(n) {
if (n == 0) {
console.log('yup');
return 'success';
}
console.log(n)
return recursion(n - 1);
//--^--
}
var x = recursion(10);
console.log(x);
Upvotes: 2