Home >Web Front-end >JS Tutorial >Detailed discussion about Recursion in JavaScript
Recursion is a technique where a function calls itself. It is a programming pattern that solves a larger problem by breaking it down into smaller problems. Using recursion in JavaScript we can do things like loop or iteration, but recursion can be simpler and more transparent to solve some problems.
Recursion has two main parts:
eg:
Factorial is the product of all positive integers from that number to 1.
function factorial(n) { // Base case: n যদি 1 হয়, তাহলে 1 রিটার্ন করো if (n === 1) { return 1; } // Recursive case: n * factorial(n-1) return n * factorial(n - 1); } console.log(factorial(5)); // Output: 120
Here, the factorial function is calling itself until n becomes 1. When n is 1, the function no longer calls itself and returns 1. This result is progressively returned through previous calls, and the original call returns 120 as the final result.
When factorial(5) is called, it will first call 5 * factorial(4) and so on until factorial(0) where the base case condition is met.
The Fibonacci series is a series of numbers where the first two numbers are 0 and 1, and each subsequent number is the sum of the two preceding numbers. For example, 0, 1, 1, 2, 3, 5, 8, …
function fibonacci(n) { // Base cases: n যদি 0 বা 1 হয়, সরাসরি n রিটার্ন করো if (n === 0 || n === 1) { return n; } // Recursive case: fibonacci(n-1) + fibonacci(n-2) return fibonacci(n - 1) + fibonacci(n - 2); } console.log(fibonacci(6)); // Output: 8
Explanation:
Answer Explanation:
এভাবে fibonacci(6) এর মান দাঁড়ায় 8, যা 6-তম ফিবোনাচি সংখ্যা।
javascriptCopy code function traverseTree(node) { console.log(node.value); node.children.forEach(child => traverseTree(child)); } const tree = { value: 1, children: [ { value: 2, children: [] }, { value: 3, children: [ { value: 4, children: [] }, { value: 5, children: [] } ] } ] }; traverseTree(tree); // Output: // 1 // 2 // 3 // 4 // 5
The above is the detailed content of Detailed discussion about Recursion in JavaScript. For more information, please follow other related articles on the PHP Chinese website!