In this shot, we learn what is recursion and how to implement it in JavaScript.
Recursion is the process of calling itself until something stops the process. In programming, a function is said to be recursive if it calls itself until something stops it.
Recursion allows us to accomplish what loops (for
/while
) do. Sometimes, the recursion approach is more elegant than using loops.
function recurse() {// function coderecurse()}recurse()
Note: The
recurse()
function calls itself inside the function (Line 3).
Note: When using a recursive function, make sure you have a stop condition (base case) to avoid the function calling itself forever and crashing your browser. This is known as infinite recursion.
In order to see how recursion works, let's write a function that will be counting down from N
to 1.
function countDownFrom(number) {// print the numberconsole.log(number)// call the function itself with number - 1countDownFrom(number - 1)}// call the functioncountDownFrom(6)
The code above looks fine, but there's an issue. However, the function is missing the stop condition. This is a typical example of infinite recursion. Let's fix the issue.
function countDownFrom(number) {// base caseif(number == 0) return// print the numberconsole.log(number)// call the function itself with number - 1countDownFrom(number - 1)}// call the functioncountDownFrom(6)
Here, we add the base case just at the beginning of the function body (line 3). If the number
is 0, end the function execution.
That's all for today. Happy coding!