0

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);

2
  • return recursion(n - 1); Commented Jan 21, 2017 at 17:06
  • 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... Commented Jan 21, 2017 at 17:13

4 Answers 4

3

You need to return recursion(n - 1);

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

0

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.

Comments

-1

change to :

return recursion(n-1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.