Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

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.

Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

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