August 2024
Intermediate to advanced
516 pages
11h 47m
English
It takes time and practice to get used to recursion, and you’ll ultimately learn two sets of skills: reading recursive code and writing recursive code. Reading recursive code is somewhat easier, so let’s get some practice with that first.
We’ll do this by looking at another example: calculating factorials.
A factorial is best illustrated with some examples.
This is the factorial of 3:
3 * 2 * 1 = 6
This is the factorial of 5:
5 * 4 * 3 * 2 * 1 = 120
And so on and so forth.
Here’s a recursive implementation that returns a number’s factorial:
| | function factorial(number) { |
| | if (number <= 1) { |
| | return 1; |
| | } else { |
| | return number * factorial(number - 1); |
| | } |
| | } |
This code can look somewhat confusing at first ...
Read now
Unlock full access