Recursion – Avoid it if possible

Recursion

				
					
/*---------NORMAL LOOP -----*/
let finalSum = 1;
for (let i = 1; i < 100000; i++) {
  finalSum += i;
}
console.log(finalSum); //4999950001

//Lets try it out using recursion

const recurAdd = (n) => {
  if (n === 0) return 0;
  else return n + recurAdd(n - 1);
};
//recurAdd(100000); //Below will give you error.. max call stack size exceeded
console.log(recurAdd(5)); //This will give you result of 15

/*****Now lets understand why --> recurAdd(100000); gives you error ****/
/*
In Recursion the function gets executed as below

f1==> 5 + recurAdd(4)
f2==> 5 + 4 + recurAdd(3)
f3==> 5 + 4 + 3 + recurAdd(2)
f4==> 5 + 4 + 3 + 2 + recurAdd(1)
f5==> 5 + 4 + 3 + 2 + 1 + recurAdd(0)
f6==> 5 + 4 + 3 + 2 + 1 + 0
result is 15

It happens as below ..nestd functions

function(5){
   return 5 + function(4) {
      return 4 + function(3) {
        return 3 + function(2){
           return 2 + function(1){
              return 1 + function(0){
                 return 0;
              }
           }
        }
      }
   }
}

*----------In Javascript --> when you execute function sequentially-----------------*

f1();
f2();
f3();


|f1() -->pushed to stack --> gets executed -->then f1() pops up
------------------------
|Global Execution Context|
------------------------


|f2() -->pushed to stack --> gets executed -->then f2() pops up
------------------------
|Global Execution Context|
------------------------

|f3() -->pushed to stack --> gets executed -->then f3() pops up
------------------------
|Global Execution Context|
------------------------
          STACK 

STACK BECOMES EMPTY --> NO OVERLOAD ON STACK ...


*--------------BUT In Javascript --> RECURSION-----------------**********

function(5){
   return 5 + function(4) {
      return 4 + function(3) {
        return 3 + function(2){
           return 2 + function(1){
              return 1 + function(0){
                 return 0;
              }
           }
        }
      }
   }
}


one by one function gets pushed to the stack till the end ..all nested functions are pushed to stack.... 
then it pops up one by one
every browser has certain limit of stack size.. 
if it exceeds , we will get max call stack exceeded
recurAdd(100000); //so this gives us error 

function(0)--pushed to stack 
function(1)--pushed to stack 
function(2)--pushed to stack 
function(3)--pushed to stack 
function(4)--pushed to stack 
function(5)--pushed to stack 
------------------------
|Global Execution Context|
------------------------
          STACK 

function(0) -->pops... then function(1) --> ...so on

*/

//So try avoid using recursion//

				
			

Leave a Comment