Table of Contents
What is recursion?
grammar
Example 1 (Use a for loop to find the sum of 1 to n numbers)
Example 2 (Use recursive function to find the sum of 1 to n numbers)
Example 3 (Iteration method to merge all strings in an array)
Example 4 (recursive method of merging all strings in an array)
Which method should the user use, iterative or recursive?
Home Web Front-end JS Tutorial How to understand recursion in JavaScript?

How to understand recursion in JavaScript?

Aug 29, 2023 pm 07:25 PM

如何理解 JavaScript 中的递归?

What is recursion?

The word recursion comes from recurring, which means going back to the past again and again. A recursive function is a function that calls itself again and again by changing the input step by step. Here, changing the input by one level means decreasing or increasing the input by one level.

Whenever a recursive function reaches a base condition, it stops its own execution. Let us understand what are the basic conditions through an example. For example, we need to find the factorial of a number. We call the factorial function by decrementing the input by 1 and need to stop whenever the input reaches 1. Therefore, here 1 serves as the basic condition.

grammar

Users can use the following syntax to understand recursion in JavaScript.

function recur(val) {
   if (base condition) {
      return;
   }
   
   // perform some action
   
   // decrease the value of val by one step
   return recur(newVal);
}
Copy after login

In the above syntax, users can observe that when the basic condition becomes true we return null to stop the execution of the function. If the base condition is false, we perform some action with the input value and call the recur() function again with the new parameter value.

Now, let’s look at various examples of recursion. Here we will learn to first implement an iterative algorithm using a for loop and then convert it into a recursive method.

Example 1 (Use a for loop to find the sum of 1 to n numbers)

In the following example, we have written the sumOfN() function to get the sum of 1 to N numbers. We use a for loop for N iterations and in each iteration we add the value of I to the sum variable.

Finally return the value of the sum variable.

<html>
<body>
   <h3>Using the <i> iterative approach </i> to find sum of n numbers in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to find the sum of n numbers using an iterative approach
      function sumOfN(n) {
         let sum = 0;
         for (let i = n; i >= 1; i--) {
            sum += i;
         }
         return sum;
      }
      content.innerHTML += "The sum of 1 to 10 numbers is " + sumOfN(10) + "<br>";
      content.innerHTML += "The sum of 1 to 20 numbers is " + sumOfN(20) + "<br>";
   </script>
</body>
</html>
Copy after login

In the above example, we use the iterative method to find the sum of N numbers. Now, we will use recursive method to do the same thing.

Example 2 (Use recursive function to find the sum of 1 to n numbers)

sumOfN() function is the recursive function in the example below. We repeatedly call the sumOfN() function by decrementing the value of the argument by 1. sumOfN(N1) returns the sum of N-1 numbers, we add N to it to get the sum of N numbers. Whenever the value of N becomes 1, it returns 1 as a base condition to stop the function execution.

<html>
<body>
   <h3>Using the <i> recursive approach </i> to find sum of n numbers in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to find the sum of n numbers using a recursive approach
      function sumOfN(n) {
         
         // base condition
         if (n == 1) {
            return 1;
         }
         
         // call function recursively by decreasing the value of n by 1.
         return n + sumOfN(n - 1);
      }
      content.innerHTML += "The sum of 1 to 10 numbers is " + sumOfN(10) + "<br>";
      content.innerHTML += "The sum of 1 to 20 numbers is " + sumOfN(20) + "<br>";
   </script>
</body>
</html>
Copy after login

Let’s understand how the above recursive function works. Below, users can learn step-by-step how recursive function calls occur.

sumOfN(5);
return 5 + sumOfN(4);
   return 4 + sumOfN(3);
      return 3 + sumOfN(2);
         return 2 + sumOfN(1);
            return 1;
         return 2 + 1;
      return 3 + 3;
   return 4 + 6; 
Copy after login

Example 3 (Iteration method to merge all strings in an array)

In the example below, we create an array of strings. We created the mergeString() function to merge all the strings of the array into one string. We use a for loop to iterate through the array and merge all the strings into the "str" ​​variable one by one.

<html>
<body>
   <h3>Using the <i> iterative approach </i> to merge all strings of the array in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to merge all strings of the array using for loop
      function mergeString(arr) {
         let str = '';
         for (let i = 0; i < arr.length; i++) {
            str += arr[i];
         }
         return str;
      }
      let arr = ['I', ' ', 'am', ' ', 'a', ' ', 'programmer'];
      content.innerHTML += "The original array is: " + arr + "<br>";
      content.innerHTML += "After merging all strings of the array into the single string is " + mergeString(arr) + "<br>";
   </script>
</body>
</html>
Copy after login

Example 4 (recursive method of merging all strings in an array)

In the example below, we have converted the mergeString() function into a recursive function. We take the first element of the array and merge it with the return result of the mergeString() function. The mergeString() function returns the last n-1 array elements after merging. Additionally, we use the slice() method to remove the first element from the array.

When there is only one element left in the array, it returns the same element as the base condition.

<html>
<body>
   <h3>Using the <i> Recursive approach </i> to merge all strings of the array in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to merge all strings of the array using recursion
      function mergeString(arr) {
         
         // based condition
         if (arr.length == 1) {
            return arr[0];
         }

         // remove the first element from the array using the slice() method.
         return arr[0] + " " + mergeString(arr.slice(1));
      }
      let arr = ["I", "am", "a", "web", "developer"];
      content.innerHTML += "The original array is: " + arr + "<br>";
      content.innerHTML += "After merging all strings of the array into the single string is " + mergeString(arr) + "<br>";
   </script>
</body>
</html>
Copy after login

Which method should the user use, iterative or recursive?

The main question is which method is better, iterative or recursive, and which method the user should use.

In some cases, iterative methods are faster than recursive methods. Additionally, recursion requires more memory during iteration. For some algorithms like divide and conquer, recursion is more useful because we need to write less code using recursive methods. Additionally, users may face memory leak issues if basic conditions are not triggered in recursive methods.

If we can break the code into smaller parts, we should use recursive methods, and to improve the performance of the code, we should use iterative methods.

The above is the detailed content of How to understand recursion in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles