Recursion Basics in JavaScript
pharia-le
Posted on October 3, 2020
What is Recursion?
The act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion). https://developer.mozilla.org/en-US/docs/Glossary/Recursion
- A function that calls itself and has a base & recursive case. The function will essentially reinvoke itself until it arrives at a result.
Two Cases Explained
- Base Case - At one point do we need to return our answer? When do we need to stop?
- Recursive Case - How do we manipulate our argument or how can we adjust the argument for another reinvocation?
Example - countSheep()
Create a function countSheep() that outputs "1 sheep..." all the way up to the input number "x sheep..."
Let's solve by using the PREP technique
- P - integer (x) for number of sheep, default argument of count = 0 to keep track of current sheep number
- R - log out sheep from 1 to x
- E - see below
// countSheep(3)
// 1 sheep...
// 2 sheep...
// 3 sheep...
- P - see below
Base Case - return when all the sheep are counted (count === x)
Recursive Case - modify count by adding 1, return a console of the current count + a reinvocation w/ x and modified count
function countSheep(x, count=0) {
// BASE CASE
// return if count equals x, which means every sheep is counted
// RECURSIVE CASE
// modify argument by adding 1 to count
// log current count & reinvoke w/ modification
}
Now, implement code logic.
function countSheep(x, count=0) {
// BASE CASE
// return if count equals x, which means every sheep is counted
if (count === x ) return;
// RECURSIVE CASE
// modify argument by adding 1 to count
count++
// log current count & reinvoke w/ modification
return console.log(x + ' sheep...') + countSheep(x, count)
}
Conclusion
When finding a recursive solution, always keep in mind what the base case and recursive case may be. It's a good way to start!
& Remember... Happy coding, friends! =)
Posted on October 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024