0

I am trying to explain to a student I am helping out at school with an ICT exam question on Javascript how the function below is returning 24. I am an economics teacher by training who dabbles in programming. I know it is a simple example of recursion but I am not sure of the actual step by step process and the scoping of the variable N. Is anyone able to explain step by step and clearly how this is working.

function mystery(n){
 if(n==0)
 return 1;
 return  n* mystery(n-1);
}

console.log(mystery(4));
2
  • 1
    Why not simply write the steps on a piece of paper? mystery(4) -> 4 * mystery(3) -> 3 * mystery(2) -> 2 * mystery(1) -> 1 * mystery(0) -> 1 => 1 * 2 * 3 * 4 (n is just a local variable) Commented Nov 30, 2019 at 11:35
  • 1
    Not related to your question, but as a matter of style, if you really must omit the {...} from a single-statement if body, then please put it on the same line as the if. It's much too liable to cause confusion otherwise (it's not instantly apparent that the second return isn't inside the if statemenet). Commented Nov 30, 2019 at 11:40

2 Answers 2

1

If you enhance the function with a bit of logging it's easy to visualize the recursion depth and the way it descends and ascends into each call:

function log(indentation) {
  var args = ['  '.repeat(indentation)]
    .concat(Array.from(arguments).slice(1));
  console.log.apply(null, args);
}

function mystery(n, depth) {
  if (n === 0) {
    log(depth, 'mystery called with n =', n, 'returning 1');
    return 1;
  } else {
    log(
      depth, 'mystery called with n =', n,
     'going into recursion: multiplying with mystery(', n - 1, ')'
    );
    var result = n * mystery(n - 1, depth + 1);
    log(
      depth, 'mystery called with n =', n,
      'returning', result, ' after recursion'
    );
    return result;
  }
}

var initialDepth = 0;
mystery(4, initialDepth);


// Output:

mystery called with n = 4 going into recursion: multiplying with mystery( 3 )
  mystery called with n = 3 going into recursion: multiplying with mystery( 2 )
    mystery called with n = 2 going into recursion: multiplying with mystery( 1 )
      mystery called with n = 1 going into recursion: multiplying with mystery( 0 )
        mystery called with n = 0 returning 1
      mystery called with n = 1 returning 1  after recursion
    mystery called with n = 2 returning 2  after recursion
  mystery called with n = 3 returning 6  after recursion
mystery called with n = 4 returning 24  after recursion
Sign up to request clarification or add additional context in comments.

Comments

1

Step by step

function mystery(n){
 console.log('n=',n); // I add this to see 'call stack'
 if(n==0) return 1;
 return n * mystery(n-1);
}

console.log(mystery(4));

// Execution looks like this
//
// 1. console.log(mystery(4));
// 2. run for n=4
//  function mystery(4){
//   if(4==0) return 1;
//   return 4 * mystery(4-1);  // we call here mystery(3)
//  }
// 3. The mystery(3) is
//  function mystery(3){
//   if(3==0) return 1;
//   return 3 * mystery(3-1);  // we call here mystery(2)
//  }
// 4. The mystery(2) is
//  function mystery(2){
//   if(2==0) return 1;
//   return 2 * mystery(2-1);  // we call here mystery(1)
//  }
// 5. The mystery(1) is
//  function mystery(1){
//   if(1==0) return 1;
//   return 1 * mystery(1-1);  // we call here mystery(0)
//  }
// 6. The mystery(0) is
//  function mystery(0){
//   if(0==0) return 1;  // we return 1 here
//   return 0 * mystery(0-1);  
//  }
//
// So at the end the  mystery(4) returns:
// return 4 * 3 * 2 *1 * 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.