John Bryant
John Bryant

Reputation: 79

JavaScript recursion function is returning is undefined

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

Answers (4)

Thomas
Thomas

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 breaking 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

Pranav C Balan
Pranav C Balan

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

Ivaylo Stoev
Ivaylo Stoev

Reputation: 487

change to :

return recursion(n-1)

Upvotes: -1

Alon Eitan
Alon Eitan

Reputation: 12025

You need to return recursion(n - 1);

Upvotes: 3

Related Questions