/    /  Javascript-Recursion

Javascript-Recursion

 

Recursion is a process of calling itself. A function that returns itself is called a recursive function(recursive()).

 

syntax:

 

function recurse() {
  // function code
  recurse();
  // function code
}

recurse();

 

The recurse() function is a recursive function. It is calling itself inside the function.

 

Javascript-Recursion

 

A recursive() must have a condition to stop calling itself. Otherwise, the function is called indefinitely.

To prevent infinite recursion, you can use the if…else statement (or similar approach) where one branch makes the recursive call, and the other doesn’t.

 

So, it generally looks like this:

 

function recurse() {
  if(condition) {
     recurse();
  }
  else {
     // stop calling recurse()
  }
}

recurse();

 

Example 1: Print Numbers

 

// program to count down numbers to 1
function countDown(number) {

  // display the number
  console.log(number);

  // decrease the number value
  const newNumber = number - 1;

  // base case
  if (newNumber > 0) {
     countDown(newNumber);
  }
}

countDown(4);

 

Output:

 

4

3

2

1

 

Example 2: Find Factorial

 

// program to find the factorial of a number
function factorial(x) {

  // if number is 0
  if (x === 0) {
     return 1;
  }

  // if number is positive
  else {
    return x * factorial(x - 1);
    }
}

const num = 3;

// calling factorial() if num is non-negative
if (num > 0) {
   let result = factorial(num);
   console.log(`The factorial of ${num} is ${result}`);
}

 

Output:

 

The factorial of 3 is 6

 

We have call function factorial() with a positive integer, it will recursively return itself by decreasing the number.