Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

The Base Case

Let’s continue our walkthrough of the countdown function. We’ll skip a few steps for brevity…

Step #21: We call countdown(0).

Step #22: We print number (i.e., 0) to the console.

Step #23: We call countdown(-1).

Step #24: We print number (i.e., -1) to the console.

Uh oh. As you can see, our solution is not perfect, as we’ll end up stuck with infinitely printing negative numbers.

To perfect our solution, we need a way to end our countdown at 0 and prevent the recursion from continuing on forever.

We can solve this problem by adding a conditional statement that ensures that if number is currently 0, we don’t call countdown() again:

 function​ countdown(number) {
  console.log(number);
 if​(number === 0) {
 return​;
  } ​else ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page