top of page

Javascript Examples using Recursion

Please grasp the idea behind Recursion here.


Reversing a String:

Where to stop: Base case.

Where to call itself: Recursive case.


When we enter "Hello" it must give "olleH".

First, 'H' is taken out --> then 'e' --> then 'l' --> then 'l' --> then 'o' --> we don't have anything to send.

After 'o', it is the base case and the rest are the recursive cases.

The recursive case is taking the character in the first place and placing it at the end of the word.
The substring() method returns the part of the string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.

function Reverse(string) {
    console.log(string)
    // Base case
    if(string === '') {
        return ''
    }
    // Recursive case - substring and charAt
    else {
        return Reverse(string.substring(1)) + string.charAt(0)
    }
}

console.log(Reverse('Hello'))

The call stack is as follows,


Checking Palindromes:

Let's take 'radar',

We know radar is palindrome.

We check first and last character in the word and if it is equal we check the next set of characters until we arrive at middle word.

Base case --> Reaching the middle word --> word length would be 1

Recursive case:

  • Checking first and last character equality.

  • If not equal --> we will return false.

  • If true --> remove the first and last from the word and send the remaining words to same function(Recuring case).

Note:

String index starts from 0.

String length starts from 1.

function isPalindrome(string) {
    // Base case --> If '' is given,length is zero
    if(string.length === 0 || string.length === 1){
        return true
    }
    // Recursive case
    if(string.charAt(0) === string.charAt(string.length - 1)) {
        // substring removes first and last character
        let removedString = string.substring(1,string.length -1)
        return isPalindrome(removedString)
    }
    else return false
}

Call-stack,


Factorial:

For 5! = 5*4*3*2*1 = 120.

It can be interpreted as 5 * 4!.

Also 0! = 1.

Base case: If 0 or 1 return 1

Recursive case:

If greater than 1,

Multiply the number by (number-1) factorial --> Therefore calling the same function with different parameters.

Yeah,that's recursion case.


function Factorial(n) {
    // Base case
    if(n === 0 || n === 1) {
        return 1
    }
    // Recuring case
    // Implementing n * (n-1)!
    else {
        return n * Factorial(n-1)
    }
}

Call-stack,


Recent Posts

See All

As there are many programming languages, there are many programming paradigms. Programming paradigm = style of programming = set of guidelines to solve the problem. So, many programming languages evol

bottom of page