What is recursion? Detailed explanation of recursion in javascript
This article brings you what is recursion? The detailed explanation of recursion in JavaScript has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. What is recursion?
The concept of recursion is very simple, "call yourself" (take a function as an example below).
Before analyzing recursion, you need to understand the concept of "call stack" in JavaScript.
2. Pushing and popping the stack
What is the stack? It can be understood that it is a certain area in the memory. This area is likened to a box. If you put something into the box, this action is pushing the stack. So the first thing to put down is at the bottom of the box, and the last thing to put down is at the top of the box. Taking something out of the box can be understood as *pushing it out of the stack.
So we come to the conclusion that we have a habit of taking things from top to bottom. The first thing to put down is at the bottom of the box, and the last thing to get is.
In JavaScript, when a function is called, stack pushing occurs. Pop occurs only when a sentence containing the return keyword is encountered or execution ends.
Let’s take an example. What is the execution order of this code?
function fn1() { return 'this is fn1' } function fn2() { fn3() return 'this is fn2' } function fn3() { let arr = ['apple', 'banana', 'orange'] return arr.length } function fn() { fn1() fn2() console.log('All fn are done') } fn()
A series of stack pushing and popping behaviors occurred above:
1. First, the stack (box) is empty at the beginning
2. Function fn is executed, fn is pushed onto the stack first and placed at the bottom of the stack (box)
3. Inside function fn, function fn1 is executed first, and fn1 is pushed onto the stack above fn
4. Function fn1 is executed, and when Go to the return keyword, return this is fn1, fn1 is popped off the stack, and now only fn
5 is left in the box. Return to the inside of fn, after fn1 is executed, function fn2 starts to execute, and fn2 is pushed onto the stack, but after Inside fn2, when fn3 is encountered, fn3 starts to be executed, so fn3 is pushed onto the stack
6. At this time, the order from bottom to top in the stack is: fn3
7. By analogy, when a sentence with the return keyword is encountered inside function fn3, fn3 pops out of the stack after execution and returns to function fn2. fn2 also encounters the return keyword and continues to pop out of the stack.
8. Now there is only fn in the stack. Return to the function fn. After executing the console.log('All fn are done') statement, fn pops out of the stack.
9. Now the stack is empty again.
The above steps are easy to confuse people. Here is the flow chart:
Let’s look at the execution in the chrome browser environment:
3. Recursion
Let’s first look at simple JavaScript recursion
function sumRange(num) { if (num === 1) return 1; return num + sumRange(num - 1) } sumRange(3) // 6
The above code execution sequence:
1. Function sumRange(3) is executed, sumRange(3) is pushed onto the stack, and the return keyword is encountered, but it cannot be popped out of the stack immediately because the call SumRange(num - 1) is sumRange(2)
2. Therefore, sumRange(2) is pushed onto the stack, and so on, sumRange(1) is pushed onto the stack,
3. Finally, sumRange(1) pops the stack and returns 1, sumRange(2) pops the stack, returns 2, sumRange(3) pops the stack
4, so the result of 3 2 1 is 6
Look at the flow chart
So, recursion is also a process of pushing and popping the stack.
Recursion can be expressed as non-recursive. The following is the equivalent execution of the above recursive example
// for 循环 function multiple(num) { let total = 1; for (let i = num; i > 1; i--) { total *= i } return total } multiple(3)
4. Notes on recursion
If the above Modify the example as follows:
function multiple(num) { if (num === 1) console.log(1) return num * multiple(num - 1) } multiple(3) // Error: Maximum call stack size exceeded
There is no return keyword sentence in the first line of the above code. Because there is no termination condition for recursion, it will always be pushed onto the stack, causing a memory leak.
Recursion prone error points
No termination point is set
Except for recursion, other parts Code
When is recursion appropriate
Okay, the above is the concept of recursion in JavaScript.
The following are practice questions.
6. Practice questions
1. Write a function that accepts a string and returns a string. This string is the inversion of the original string.
2. Write a function that accepts a string and compares one character from the front to the back. If the two are equal, return true; if they are not equal, return false.
3. Write a function that accepts an array and returns a flattened new array.
4. Write a function that accepts an object. If the object value is an even number, add them together and return the total value.
5. Write a function that accepts an object and returns an array. This array includes all the values in the object which are strings
7. Reference answer
Reference1
function reverse(str) { if(str.length <p>Reference2</p><pre class="brush:php;toolbar:false">function isPalindrome(str){ if(str.length === 1) return true; if(str.length === 2) return str[0] === str[1]; if(str[0] === str.slice(-1)) return isPalindrome(str.slice(1,-1)) return false; } var str = 'abba' isPalindrome(str)
Reference3
function flatten (oldArr) { var newArr = [] for(var i = 0; i <p>Reference4</p><pre class="brush:php;toolbar:false">function nestedEvenSum(obj, sum=0) { for (var key in obj) { if (typeof obj[key] === 'object'){ sum += nestedEvenSum(obj[key]); } else if (typeof obj[key] === 'number' && obj[key] % 2 === 0){ sum += obj[key]; } } return sum; } nestedEvenSum({c: 4,d: {a: 2, b:3}})
Reference5
function collectStrings(obj) { let newArr = [] for (let key in obj) { if (typeof obj[key] === 'string') { newArr.push(obj[key]) } else if(typeof obj[key] === 'object' && !Array.isArray(obj[key])) { newArr = newArr.concat(collectStrings(obj[key])) } } return newArr } var obj = { a: '1', b: { c: 2, d: 'dd' } } collectStrings(obj)
5. Summary
The essence of recursion is that you often have to think about the regular part first. When considering the recursive part, the following are the methods commonly used in JavaScript recursion
Array: slice, concat
String : slice, substr, substring
Object: Object.assign
The above is the detailed content of What is recursion? Detailed explanation of recursion in javascript. For more information, please follow other related articles on the PHP Chinese website!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)
