JavaScript Recursion

Michael Abe
2 min readSep 30, 2021

In coding there are many times where we need a function to continue running until we don’t. While this may sound confusing, the principal is used when sorting and doing other tasks that have a defined ending. By rule, a recursive function will always have at least one condition. The hallmark of a recursive function is a condition that when met will stop calling itself. Otherwise, the function will call itself.

The example above is a basic recursive function. Let’s go over this function line by line.

  1. We are declaring a function called ‘down’. The function takes in an argument (in this case it is meant to take an an integer denoted by ‘number’).
  2. Here we are logging to the console our integer.
  3. Line 3 declares a variable ‘num’ that is set equal to the integer that we are receiving as an argument and subtracting one from that number, we are essentially declaring a reverse counter.
  4. Here is the condition that we are setting. What we are saying here is that as long as the ‘num’ counter that we declared on line three is greater that than integer ‘0’ than we want to continue.
  5. This line is code block that we are asking to be run if the condition that was set in the line above has been met. In this case if the number that our counter is reading out at is above ‘0’ we will be running our ‘down’ function over and over again.
  6. This is the closing curly bracket for our if statement code block.
  7. The closing curly bracket for our ‘down’ function declared on line 1.

The condition that makes this a recursive function is the fact that the function keeps calling on itself unless the counter is ‘0’ or less. While this is a simple countdown function that logs the below it’s argument to the console, it is a great example of a recursive function.

--

--