Sample Video Frame

25: Functions and Recursion

In JavaScript you have the ability to do something called "recursion", but it's not a very safe thing to do. Recursion is where a function calls itself, and by doing that creates a loop. In JavaScript this causes a new function call, which means if you do it too much you run out of memory and cause a crash. However, if you are going to learn about "functional programming" you need to know how recursion works.

Consider this exercise a novelty that you shouldn't really use.

The Code

Recursion is very simple but many beginners get confused that it actually works. To them it seems odd that a function can call itself. There's nothing odd about it because you can usually combine features of a language, and calling a function is one of those features. Once you realize that this is possible you can create very complicated ways of looping that do not need for-of or while-loop style of processing.

In this code I simply loop over a range of numbers using recursion, and then do a more complex version that uses a callback.

// simple recursive counting function
const counter = (i, upto) => {
  if(i < upto) {
    console.log("counter", i, upto);
    counter(i+1, upto);

// use counter to just print out 1-5
counter(1, 5);

// a more complex counter that can call a callback
const cb_counter = (i, upto, cb) => {
  if(i < upto) {
    cb(i, upto);
    cb_counter(i+1, upto, cb);

// do the same thing but with a callback
cb_counter(1, 6, (i, j) => {
   console.log(i, j)

I recommend you watch the video as I actually draw out how recursion works visually.

What You Should See

When you run this you see the output of both functions:

$ node "code.js" 
counter 1 5
counter 2 5
counter 3 5
counter 4 5
1 6
2 6
3 6
4 6
5 6

Learn JavaScript Today

Register today for the Early Access course and get the all currently available videos and lessons, plus all future modules for no extra charge.

Still Not Sure? Try the next FREE Lesson!