Recursion Vs Iteration in JavaScript

Basically, recursion and iteration are used to execute sets of instructions. In JavaScript, a program that calls itself its said to be a recursive program and iterative program is when a loop is repeatedly executed. In simple term, Recursion is when the output of one iteration becomes the input of the next one in other words the method being called is the same as the one making the call. while Iteration is said to have occurred when the same step/procedure/cycle is repeated multiple times in the same way. The loop in iteration could be “for”, “while” or “do…” loop. For a ‘for loop’ to be executed it has to be follow this pattern — For (‘a given condition’){do something}, Note that the condition must be a repetitive condition for a loop to be used. Example of a ‘for loop’.

‘for loop’

when you run this “for loop” example above the result will be terminated at 12. but when sum sum (increment) changes to minus minus, it becomes an infinite loop and it will keep running indefinitely except it is terminated manually.

Second example using factorial:

Iteration and Recursion Example (The first box is for Iteration while the Second is for Recursion)

From the second example, we see that when you call factorial (3), the function will return 6 using iteration, same applies to recursion although the output is gotten from different methods. hence, we see very different ways of solving problem but getting the same result. Hence, selecting which method to use is totally up to you depending on what you want.

lets consider some differences between Recursion and Iteration.

--

--

Nwobodo Maureen Amuche

I am a Public Health professional with interest in data analysis and data science.