Recursion
Recursion
is a technique based on the divide and conquer
principle. That principle calls for us to define the solution of a bigger problem in terms of the solution of a smaller version of itself.
In a programming language, a recursive function is one that calls itself. Let's look at the pseudo-code of a recursive function that prints the numbers from 1
to 5
. You can invoke the function printList
like printList(1)
.
The code is pretty cool as it will, like our iterative counterpart, also print the numbers 1, 2, 3, 4, 5
. printList
is a recursive function as it calls itself. We'll learn how it works in a bit.
xxxxxxxxxx
10
function printList(i) {
// Base case: If i is greater than 5, return without doing anything
if (i > 5) {
return; // Do nothing
}
// Recursive case: Print the value of i
console.log(i);
// Call the function with i + 1
printList(i + 1);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment