DEV Community

Cover image for Recursion in JS
aiman9411
aiman9411

Posted on

Recursion in JS

What is recursion?

Recursion is a process to call itself and function that calls itself is termed as recursive function. (Warning: someone needs to stop it or else it will call itself for infinite time).

patrick_recurse

Recursive function

In a recursive function, there are two parts that we need to include: base case (a condition that tells the function to stop) and the recursive call. Generally, recursive function is written using if...else statement since we can easily write one branch as recursive call and the other as the base case. ****

function countup(n) {
    // this is the base condition
  if (condition) {
    return xyz;
    // this is the recursive call
  } else {
    return countup(n-1)
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's call the function!

Enough with the explanation and let's try to see how the magic works. Below is the recursive function that returns an array containing the number 1 until n. Also, this function receives an argument, n, representing the final number.

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

How does it work? The answer is it will need to call itself with progressively smaller values until it reaches 1.

// This is how it works
countup(5)
    countup(5-1)
        countup(4-1)
            countup(3-1)
                countup(2-1)
                    countup(1-1) // this will be evaluated to (n < 1) and function will return []
                                             // then function will push n of every stage into the empty array
Enter fullscreen mode Exit fullscreen mode

Pop Quiz Time!

To ensure we understand the concept, let's try to answer these two questions. (Another warning: I named the function with ambiguous names as xyz and abc because it's pop quiz time. If not, then I will name it based on what it does.)

Question 1: What is the result when we call xyz function?

function xyz(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = xyz(n - 1);
    countArray.unshift(n);
    return countArray;
  }
}

console.log(xyz(5)
Enter fullscreen mode Exit fullscreen mode

Question 2: What is the result when we call opq function?

function opq(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
  } else {
    var numbers = opq(startNum, endNum - 1);
    numbers.push(endNum);
    return numbers;
  }
}

console.log(opq(1,5));
Enter fullscreen mode Exit fullscreen mode

Question 3: What will happen when we call cde function?

function xyz(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = xyz(n + 1);
    countArray.unshift(n);
    return countArray;
  }
}

console.log(xyz(3))
Enter fullscreen mode Exit fullscreen mode

Clue for Question 3:
is-this-a-recursive

Active recall session

I have prepared some questions so that we can recall the concept together. If you revisit this note next time, then you might just want to skip the explanation part and head straight to these questions.

  1. What is recursion?
  2. How many parts generally we include in a recursive function?
  3. What will happen if we failed to include base condition in the function?

Last but not least...

I hope you enjoyed and benefited from this note. If you find this note is not helpful, then keep on googling and adding comments to your own note. All the best!

788f27edb761cb3e6af9422ece19fcc4

Answer for pop quiz questions

  1. It's a countdown function. Result should be [ 5, 4, 3, 2, 1]
  2. It's a range of number function. Result should be [ 1, 2, 3, 4, 5]
  3. Result is "RangeError: Maximum call stack size exceeded". This is because we coded it as (n+1) instead of (n-1). Hence, it will never stop.

Top comments (0)