August 2024
Intermediate to advanced
516 pages
11h 47m
English
Let’s say you work at NASA and need to program a countdown function for launching spacecraft. The particular function that you’re asked to write should accept a number—such as 10—and display the numbers from 10 down to 0.
Take a moment and implement this function yourself. When you’re done, read on.
Odds are that you wrote a simple loop, along the lines of this implementation:
| | function countdown(number) { |
| | while (number >= 0) { |
| | console.log(number); |
| | number -= 1; |
| | } |
| | } |
Nothing is wrong with this implementation, but it may have never occurred to you that you don’t have to use a loop.
How?
Let’s try recursion instead. Here’s a first attempt at using recursion to implement our countdown function:
| | function countdown(number) ... |
Read now
Unlock full access