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.
function factorial( num )
if( num <= 1 )
return num * (factorial( num - 1 ));
var foo = factorial( 5 );
document.write( foo );
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.