Wednesday , 17 January 2018
Home / Programming / JavaScript / Recursive Functions – Advanced JavaScript Tutorial
Recursive Functions
Recursive Functions

Recursive Functions – Advanced JavaScript Tutorial

We’re going to stop talking about object oriented programming for now. Let’s focus on functions. There’s a thing called recursive functions. It’s just a function that calls on itself until a condition has been met. Almost like a loop.

Setting Up The Script

Clear your script and add this bit of code.

If you don’t know what factorials are, then it’s time for a math lesson! A factorial is the result of a number being multiplied by numbers that descends before it. So, we if had a number like 5, then you would get 120. Here’s how the math is done.

5! = 5 * 4 * 3 * 2 * 1 = 120

In our script, we have a function that takes in a number. If this number is less than or equal to 1, then we just return 1. We check for numbers lower than 1 because you can’t have negative numbers for factorials.

If it’s a positive integer above 1, then we actually end up calling the function again. Except the number’s value is decreased by 1. This will run continuously until the number is 1. Once that happens, then all functions will get the correct returns and eventually you get the final value.

We create variable called foo that will hold the value returned by the factorial() function that’s passed in the number 5. We then output this variable and you should get 120.

Recursion vs Loops

Recursive functions and loops can both provide the same results. For the most part, loops are meant to well…loop. It’s the most favourable path. However, recursion functions can be useful when it comes to readability. The simpler the job, the simpler it is to read.


This tutorial was just meant to show you another way of looping using recursion functions. Just stick to loops if recursion seems complicated. No harm done. For more information about recursion, then check out the link below.

About Jasko Koyn

Check Also

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to learn how to create web applications with Node.js and SQL? Check out my course!
Get 93% off my course. You'll also learn how to build real world applications using Node and SQL. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!