Recursion in JavaScript
Recursion is an important programming technique, in which a function calls itself to solve some problem. A method that uses this technique is recursive. Many programming problems can be solved only by recursion, and some problems that can be solved by other techniques are better solved by recursion.
To prevent infinite recursion, you need an if-else statement where one branch makes a recursive call, and the other branch does not. The branch without a recursive call is usually the base case which do not make recursive calls to the function and prevents an infinite loop from occuring.
You may remember from math class that the factorial of a number n is the product of all positive integers less than or equal to n. In other words, the factorial of 5 is 5 x 4 x 3 x 2 x 1. The mathematical notation for this is 5!.
function factorialize(num) {
// Negative numbers are not allowed
if (num < 0) {
return 0;
}
// Zero = 0 and One = 1
if (num === 0 || num === 1) {
return 1;
}
// Multiple the number by the next lower number
return num * factorialize (num - 1);
}
factorialize(5);
In JavaScript, if a function calls itself recursively then the JavaScript engine has to create what’s called a new ‘stack’. A stack is a chunk of memory allocated to help keep track of all the information related to the function at the point of execution (such as its arguments and their initialised values).
Here in lies the problem: creating stacks is expensive, as the JavaScript engine can only create as many stacks as it has memory available. If we write a function that recursively calls itself many times then we’ll find that we can exhaust the memory allocation and trigger an error.
Next: Using jQuery Event Triggers in your coding.