A recursive function is a function that calls itself. The following code shows a simple example of recursion.
function trouble(){
trouble();
}
A recursive function like above calls itself unconditionally, cause infinite recursion. To prevent this from happening, practical recursion functions call themselves only while a given condition is met.
Here, to compare the use of recursive function and normal loop function, I will use a simple example to calculate the mathematical factorial of a number.
Approach 1 – Using recursive way
function factorial (n){
if (n<0){ return; }else{ return n*factorial(n-1); } }
Approach 2 – Using looping without recursion
function factorial(n){
if(n<0){ return; }else{ var result=1; for(var i=1;i<=n;i++){ result=result*i; } return result; } }
Function recursion is considered elegant because it provides a simple solution – calling the same function repeatedly – to solve a complex problem. However, repeated function calls are less efficient than loop iterations . The non-recursive approach to calculate factorials is many times more efficient than the recursive approach, which also provides the Flash runtime’s maximum recursion limit (default 1000), but can be set via the compiler argument default-script-limits.
From personal likeness, I prefer looping iteration than recursion.
Hi,
Do you know if there is any tutorial examples using the codes comparisons above.
Thx…
J