Recursion in Javascript
agrem28
Posted on September 24, 2020
Functions are the cornerstone of Javascript programming. Nearly all applications of Javascript code are chock full of functions of all kinds. One type of function structure is the recursive function.
By definition, a recursive function is a function that calls itself within it. This way the function creates a loop.
function printRecursive(x) {
console.log(x);
printRecursive(x);
}
recursion(3);
This example will keep printing 3. But how do we end the loop? We do this by using a test. When calling the function recursively, change the arguments such that the test will eventually be passed. Then return the function and the loop will be broken. This test is called the base case.
function printRecursive(x, times) {
if (times === 0) { // base case
return;
}
console.log(x);
printRecursive(x, times-1);
}
printRecursive(3, 3);
This example will print 3 three times. When printRecursive(3, 3)
is called, the test fails because 5 does not equal 0 and 3 is printed. Then printRecursive
is called again with the arguments (x, times-1)
. Once again the test fails because 4 does not equal 0 and 3 is printed. This continues until times is 0 in which case the loop is broken.
Posted on September 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024