DEV Community

Nashmeyah
Nashmeyah

Posted on

Recursive functions

Recursive functions are functions that call themselves over and over again until a base condition is met, eezy-peezy lemon squeezy... or is it?

Let start with some simple code to get the ball rolling

function printDownFrom(num) {
  console.log(num)
  if(num > 1) {
    printDownFrom(num - 1) // recursive call
  }else {
    return true //base condition
  }
}

printDownFrom(4)
//4
//3
//2
//1
Enter fullscreen mode Exit fullscreen mode

As you can see above, this is a function that takes in a number and the first line it is asked to print the number. The second line is determining whether that number is greater than 1, that way we can see if we can subtract from that number and print the number again because the goal or "base case" for this function is to count down all numbers starting with the condition inserted.

After that line of code, if the condition is true we call our function from within our function telling it to run again, thus printing the next number after we subtracted. This process repeats until the first if statement condition is false breaking our recursion.

Lets do something a bit harder, what if we want to print all the letters individually from one to the next initially spelling out the word.

function printString(string) {
  console.log(string[0]);

  if (string.length > 1) {
    let myNewString = string.substring(1, string.length);
  printString(myNewString); //recursive call
  } else {
   return true; //base case
  }
}
Enter fullscreen mode Exit fullscreen mode

Similar task to the above code, but changing a step we are calling the function based off the remainder of the string after we call the .substring method which removes the first letter because we are telling it to start from index 1 and not index 0. Each time we are reassigning myNewString with the new information and printing the first letter.

I hope this makes sense! Thank you all for reading, I hope you have a wonderful day.

Top comments (0)