In JavaScript, a recursive function is a function that calls itself in order to solve a problem. Recursive functions break down a problem into smaller, more manageable sub-problems, and they solve each sub-problem by applying the same logic.
Here are the key components of a recursive function:
- Base Case: A condition that stops the recursion. It’s the simplest form of the problem that can be solved directly without further recursion.
- Recursive Case: The part of the function that calls itself with a smaller or simpler input. This is where the problem is broken down into sub-problems.
Here’s a generic template for a recursive function in JavaScript:
function recursiveFunction(parameter) { // Base case if (/* base case condition */) { // Do something simple and return return something; } else { // Recursive case // Break down the problem, call the function with a smaller input return recursiveFunction(simplerInput); } }
If you add console.log(n);
inside the else
block of your factorial
function, it will print the value of n
each time the function is called. However, keep in mind that this will print the values in reverse order due to the nature of recursion. Here’s the modified code:
function factorial(n) { // Base case: factorial of 0 or 1 is 1 if (n === 0 || n === 1) { return 1; } else { // Recursive case: n! = n * (n-1)! console.log(n); // Print the value of n return n * factorial(n - 1); } } // Example usage: const result = factorial(5); console.log(result); // Output: 120
When you run this code, you’ll see the following output in the console:
5 4 3 2 1
Here are three more examples of recursive functions in JavaScript:
Example 1: Sum of Natural Numbers
function sumOfNaturalNumbers(n) { // Base case: sum of first natural number is 1 if (n === 1) { return 1; } else { // Recursive case: sum(n) = n + sum(n-1) return n + sumOfNaturalNumbers(n - 1); } } // Example usage: const sumResult = sumOfNaturalNumbers(5); console.log(sumResult); // Output: 15
This recursive function calculates the sum of the first n
natural numbers.
Example 2: Fibonacci Sequence
function fibonacci(n) { // Base case: fibonacci(0) = 0, fibonacci(1) = 1 if (n === 0) { return 0; } else if (n === 1) { return 1; } else { // Recursive case: fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) return fibonacci(n - 1) + fibonacci(n - 2); } } // Example usage: const fibResult = fibonacci(6); console.log(fibResult); // Output: 8
This recursive function generates the nth number in the Fibonacci sequence.
Example 3: Power Function
function power(base, exponent) { // Base case: any number to the power of 0 is 1 if (exponent === 0) { return 1; } else { // Recursive case: power(base, exponent) = base * power(base, exponent - 1) return base * power(base, exponent - 1); } } // Example usage: const powerResult = power(2, 3); console.log(powerResult); // Output: 8