Recursion in JS
Tags: javascript
Published: 2021-01-25 01:09:26

#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](https://dev-to-uploads.s3.amazonaws.com/i/h5wafuqu3mdc9hplrmlh.jpeg)
 

## 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. ****

```jsx
function countup(n) {
	// this is the base condition
  if (condition) {
    return xyz;
	// this is the recursive call
  } else {
    return countup(n-1)
  }
}
```

## 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. 

```jsx
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 ]
```

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

```jsx
// 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
```

## 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?**

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

console.log(xyz(5)
```

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

```jsx
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));
```

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

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

console.log(xyz(3))
```

**Clue for Question 3:**
![is-this-a-recursive](https://dev-to-uploads.s3.amazonaws.com/i/kpjb035zqs9cdvarmecc.jpg)
   
## 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](https://dev-to-uploads.s3.amazonaws.com/i/m88to7lpx8vfktquhn4a.jpg)
 

## 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.