A recursive function in JavaScript is a function that calls itself within its body. Recursion is a powerful tool for solving problems that can be broken down into smaller subproblems.
Recursive function example:
function countdown(num) { if (num <= 0) { console.log("Done!"); } else { console.log(num); countdown(num - 1); } } countdown(5);
Calling countdown(5) will print a sequence of numbers from 5 to 1 to the console, followed by the message “Done!“.
This example uses the countdown function to count down from a given number to zero. If num is less than or equal to zero, the function displays the message “Done!“.
Otherwise, it prints the current number and calls itself with the argument num – 1.
Recursive functions can be useful for solving problems such as calculating a factorial, searching for elements in a tree, or traversing data structures.
However, it is important to be careful when using recursion to avoid an infinite loop and to correctly define a base case that will stop recursive calls.
Self-calling functions in JS. Code example
July 25, 2022