Get a Quote Right Now

Edit Template

Recursion

Recursion:A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).

For example, consider the following loop:

This is while loop syntax to print //0123456789

let x = 0;
// “x < 10” is the loop condition
while (x < 10) {
// do stuff
x++;
}

This is recursion way to print //0123456789
function loop(x) {
// “x >= 10” is the exit condition (equivalent to “!(x < 10)”)
if (x >= 10) {
return;
}
// do stuff
console.log(x);
loop(x + 1); // the recursive call
}
loop(0);

Share

Leave a Reply

Your email address will not be published. Required fields are marked *