In programming recursion is a way of looping.
We have loop constructs such as while,
do while, and for in most
if not all programming languages. Some problems,
however, are by definition recursive, and solving
them as such means coding the solution in a manner
that is true to the verbal definition.
Take the mathematical concept of faculty
, widely used in probability and
statistics, and important in understanding
aspects of security. In math n faculty
is written as n!, its meaning is
n! = n * (n-1) * (n-2) * ... * 2 * 1 # as in 5! = 5 * 4 * 3 * 2 * 1
Faculty has a recursive definition that is clear from the above:
n! = n * (n-1)!
The crucial thing here is that faculty is defined in terms of itself. In JavaScript as in other languages recursion is expressed as a function calling itself from somewhere in its code.
'use strict';
const doIt = function () {
// some code
doIt();
}
If you are suspicious, rightly so, this is an endless loop. As in all loops we need to control it for it to stop eventually.
'use strict';
const doIt = function () {
if (endCondition) {
return someValue;
}
// some code
doIt();
}
A commonly used example from many tutorials, here lifted from [Dow16]:
'use strict';
const countdown = function(n) {
if (n === 0)
console.log('Go!');
else {
console.log(n);
countdown(n - 1);
}
}
countdown(7);
You may try it from your browser console.