The Wayback Machine - https://web.archive.org/web/20240717180319/https://www.geeksforgeeks.org/how-to-understand-recursion-in-javascript/
Open In App

How to Understand Recursion in JavaScript ?

Last Updated : 26 Jul, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In this article, we will understand the basic details which are associated with the understanding part as well as the implementation part of Recursion in JavaScript.

Let us first understand what exactly is Recursion.

Recursion:

  • We could define recursion formally in simple words, that is, function calling itself again and again until it doesn’t have left with it anymore.
  • We may think of recursion (informally) as like running on a racing track again and again but each time the laps getting smaller and smaller.
  • As we have seen that recursion is function keep calling itself again and again and eventually gets stopped at its own, but we may also realize a fact that a function doesn’t stop itself.
  • Therefore to make function stop at some time, we provide something calling Base Case, which lets any function realize that “Yes, its time to get terminated!”.
  • After giving the base case condition, we implement the recursion part in which we call function again as per the required result.
  • Some common examples of recursion includes “Fibonacci Series”, “Longest Common Subsequence”, “Palindrome Check” and so on.
  • We may also think recursion in the form of loop in which for every user passed parameter function gets called again and again and hence produces its output as per the need,

Now that we have understood all the basic things which are associated with the recursion and its implementation, let us see how we could implement it by visualizing the same through the following examples-

Example 1: In this example we will be implementing a number decrement counter which decrements the value by one and prints all the numbers in a decreasing order one after another.

Javascript




<script>
    let decrementCounter = (number) => {
 
        // Base case condition....
        if(number === 0) return ;
        console.log(number);
        decrementCounter(number - 1);
    }
    decrementCounter(5);
</script>


Output:

5
4
3
2
1

Example 2: In this example, we will be developing a code that will help us to check whether the integer we have passed is Even or Odd. By continuously subtracting 2 from a number, the result would be either 0 or 1. So if it is 0 then our number is Even otherwise it is Odd.

Javascript




<script>
    let checkNumber = (number) => {
 
        // Two base case conditions.....
        if(number === 0) return (number + " is even");
        if(number === 1) return (number + " is odd");
        return checkNumber(number - 2);
    }
    console.log(checkNumber(5));
    console.log(checkNumber(10));
    console.log(checkNumber(13333));
</script>


Output:

1 is odd
0 is even
1 is odd


Previous Article
Next Article

Similar Reads

How to understand WeakMap in JavaScript ?
The WeakMap object stores key/value pairs. The keys should be objects, and also the value may be anything. In JavaScript, a map API may be engineered with 2 arrays, one for keys and one for values that are shared by the four API functions. Setting parts on this map would entail at the same time inserting a key and value onto the top of every one of
3 min read
What to understand the Generator function in JavaScript ?
Generators generate value on the fly which means whenever there is a need for that value then only it will be generated. It means the value is generated but not stored in memory so it takes less time to execute. It uses asterick (*) symbol after the keyword function i.e. function* to tell javaScript it is a generator function. The generator functio
4 min read
How to understand various snippets of setTimeout() function in JavaScript ?
When dealing with JavaScript, there will be times when you wish to run a function after a particular period of time. For this, we use setTimeout(), an asynchronous method that sets a timer, which then executes the function or specified piece of code once the timer expires. In this article, we will be exploring several code snippets on how setTimeou
3 min read
What to understand Callback and Callback hell in JavaScript ?
JavaScript, a single-threaded language, relies on callbacks for handling asynchronous tasks. Callbacks execute code once an operation finishes. But as the code complexity increases, the risk of callback hell emerges. Callback: A callback is a function that is passed as an argument to another function that executes the callback based on the result.
2 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
What to understand about Responsive Websites ?
Websites that can change their appearance dynamically according to the device or the screen in which it is viewed are called responsive websites. It uses the concept of breakpoints to determine the appearances of websites on different screens. Breakpoints are specified on the basis of the width of the device's browser which means the experience on
4 min read
What do you understand by the HTTP Status Codes ?
The HTTP or the HyperText Transfer Protocol is a protocol of the application layer. It helps in establishing communication between a web browser and a web server. When a client requests any information, the browser sends a response using numeric status codes. These status codes are in the form of 3-digit numbers ranging from 100 - 599. The client t
3 min read
What to understand Pure CSS Responsive Design ?
In this article, we will learn about Pure.CSS responsive design. It is a collection of responsive CSS modules that can be included in any web application to create faster, beautiful, and responsive websites. In simple words, it is a framework of CSS that is used to build a beautiful and responsive website in less time. Pure CSS is a CSS framework t
3 min read
What do you understand by Virtual DOM ?
The Virtual DOM is an in-memory representation of the DOM. DOM refers to the Document Object Model that represents the content of XML or HTML documents as a tree structure so that the programs can be read, accessed and changed in the document structure, style, and content. Prerequisites:DOMHTMLReact JS ReactDOMLet's see how a document is parsed by
3 min read
React MUI Understand MUI Packages
MUI is the abbreviation for "Material-UI", which is a popular React-based UI library that provides a set of React components with a wide range of specifications. MUI packages provide a set of components implementing the Material Design guidelines. These components include UI elements such as buttons, forms, and navigation elements that are designed
4 min read
Practice Tags :
three90RightbarBannerImg