Recursion
function call themselves - Screenshot from Fun Fun Function
makeTree(categories, null) - Screenshot from Fun Fun Function
Recursion is a technique in programming where a function calls itself repeatedly until a specific condition is met. This allows solving complex problems by breaking them down into smaller, easier to solve sub-problems.
In JavaScript, a recursive function has a base case, which is the condition that stops the recursion, and a recursive case, which is the logic that calls the function again with a modified argument.
Hereβs an example of a recursive function that calculates the factorial of a number:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
In this example, the base case is **if (n === 0)**
, which returns **1**
and stops the recursion. The recursive case is **return n * factorial(n - 1)**
, which calls the **factorial**
function again with **n - 1**
as an argument.
Recursion can be used to solve many types of problems in JavaScript, including tree traversal, searching and sorting, and more. However, itβs important to be careful with recursion, as it can easily lead to infinite loops and stack overflow errors if the base case is not properly defined.
Video from the screenshots: http://youtube.com/watch?v=k7-N8R0-KY4