Recursion in JavaScript | JavaScript for Web Development - Software Development PDF Download

Introduction

Recursion is a powerful concept in programming that allows a function to call itself. It provides an elegant solution for solving complex problems by breaking them down into simpler, repetitive tasks. In this article, we will explore recursion in JavaScript and its applications in web development. We'll cover the basics, provide multiple examples with code explanations, and conclude with some sample problems and their solutions.

What is Recursion?

Recursion is a programming technique where a function calls itself until a certain condition is met. It provides an alternative approach to iteration, allowing us to solve problems by breaking them down into smaller subproblems.

Anatomy of a Recursive Function

A recursive function consists of two parts:

  • Base Case: It defines the condition under which the function stops calling itself and returns a value. It acts as the exit point for the recursion.
  • Recursive Case: It defines the logic where the function calls itself, typically with modified parameters, to solve a smaller version of the problem. The recursive case moves closer to the base case with each recursive call.

Example: Calculating Factorial Using Recursion

Factorial is the product of all positive integers from 1 to a given number. Let's see how we can calculate factorial using recursion.

function factorial(n) {

  // Base case: factorial of 0 or 1 is 1

  if (n === 0 || n === 1) {

    return 1;

  }


  // Recursive case: call the function with a smaller number

  return n * factorial(n - 1);

}


console.log(factorial(5)); // Output: 120

Code Explanation:

  • The 'factorial' function takes a number 'n' as input.
  • In the base case, if 'n' is 0 or 1, we return 1 since the factorial of 0 or 1 is 1.
  • In the recursive case, we call the 'factorial' function with 'n - 1' and multiply it by 'n'. This step continues until the base case is reached.

Example: Summing an Array Using Recursion

Let's explore how we can calculate the sum of an array using recursion.

function sumArray(arr) {

  // Base case: return 0 for an empty array

  if (arr.length === 0) {

    return 0;

  }


  // Recursive case: add the first element with the sum of the rest of the array

  return arr[0] + sumArray(arr.slice(1));

}


console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15

Code Explanation:

  • The 'sumArray' function takes an array 'arr' as input.
  • In the base case, if the array length is 0, we return 0 since the sum of an empty array is 0.
  • In the recursive case, we add the first element of the array ('arr[0]') with the sum of the rest of the array ('arr.slice(1)'). This step continues until the base case is reached.

5. Example: Reversing a String Using Recursion

Let's see how we can reverse a string using recursion.

function reverseString(str) {

  // Base case: return an empty string for an empty string input

  if (str === '') {

    return '';

  }


  // Recursive case: concatenate the last character with the reversed substring

  return reverseString(str.slice(1)) + str[0];

}


console.log(reverseString('hello')); // Output: 'olleh'

Code Explanation:

  • The 'reverseString' function takes a string 'str' as input.
  • In the base case, if the string is empty ('str === '''), we return an empty string.
  • In the recursive case, we concatenate the last character of the string (str[0]) with the reversed substring ('reverseString(str.slice(1))'). This step continues until the base case is reached, resulting in the reversed string.

Sample Problems and Solutions

Problem 1: Write a recursive function to find the nth Fibonacci number.

function fibonacci(n) {

  if (n <= 1) {

    return n;

  }


  return fibonacci(n - 1) + fibonacci(n - 2);

}


console.log(fibonacci(6)); // Output: 8

Problem 2: Write a recursive function to check if a given string is a palindrome.

function isPalindrome(str) {

  if (str.length <= 1) {

    return true;

  }


  if (str[0] !== str[str.length - 1]) {

    return false;

  }


  return isPalindrome(str.slice(1, -1));

}


console.log(isPalindrome('racecar')); // Output: true

Conclusion

Recursion is a powerful technique that allows us to solve complex problems by breaking them down into simpler subproblems. In JavaScript, we can leverage recursion to perform various tasks, such as calculating factorials, summing arrays, and reversing strings. By understanding the anatomy of a recursive function and practicing with sample problems, you can enhance your problem-solving skills in web development and beyond.
Remember, recursion should be used judiciously, considering factors like performance and stack size limitations. However, when applied correctly, recursion can provide elegant solutions to a wide range of problems in JavaScript and other programming languages. 

The document Recursion in JavaScript | JavaScript for Web Development - Software Development is a part of the Software Development Course JavaScript for Web Development.
All you need of Software Development at this link: Software Development
51 videos|28 docs|12 tests

Top Courses for Software Development

51 videos|28 docs|12 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Previous Year Questions with Solutions

,

Viva Questions

,

Semester Notes

,

practice quizzes

,

Recursion in JavaScript | JavaScript for Web Development - Software Development

,

Objective type Questions

,

Sample Paper

,

shortcuts and tricks

,

mock tests for examination

,

video lectures

,

Summary

,

Important questions

,

study material

,

pdf

,

ppt

,

Recursion in JavaScript | JavaScript for Web Development - Software Development

,

past year papers

,

Extra Questions

,

Free

,

Recursion in JavaScript | JavaScript for Web Development - Software Development

,

MCQs

,

Exam

;