Recursion

Steps in writing recursive function

  1. Identify a Base Case
    • the base case is the case in which we decide there is no more work for us to do and it's time to return and stop the recursion process
  2. Do some amount of work
  3. Call the function again
    • When we call the same function again, it's extremely critical to make sure that we have change the argument(s) in some fashion
    • Otherwise, we will enter an infinite loop
    • Make sure that whatever returned by the function will eventually get to the Base Case

Recursive Tips: Diagram 04 tab 12

code

In [1]:
function printNumber(n, dec = 1){ // default parameter
  if (n === 0){ // Base Case
    return;
  }
  
  console.log(n);
  printNumber(n - dec); // Recursive step
  
}

printNumber(10);
10
9
8
7
6
5
4
3
2
1