Search

Recursive vs Iterative Functions

Iteration vs Recursion


The concepts can sometimes be used interchangeably and they are very similar.


The concept of Recursion and Iteration is to execute a set of instructions repeatedly. The difference between them is that recursion is simply a method call in which the method being called is the same as the one making the call while iteration is when a loop is repeatedly executed until a certain condition is met. Under the hood, both recursion and iteration depends on a condition so as to know when to stop but recursion is simply a process, always applied to a function.


An example of recursion is shown below:

function factorial(number) { 
    if (number === 1) { 
        return 1; 
    } 
    return number * factorial(number - 1);
}
view rawrecursion.js hosted with ❤ by GitHub

and here’s an example of iteration:

var step;
for (step = 0; step < 5; step++) { 
// Runs 5 times, with values of step 0 through 4. 
console.log('Walking east one step');
}
view rawiteration.js hosted with ❤ by GitHub

Key Differences between Recursion and Iteration


  • A conditional statement decides the termination of recursion while a control variable’s value decide the termination of the iteration statement (except in the case of a while loop).

  • Infinite recursion can lead to system crash whereas, infinite iteration consumes CPU cycles.

  • Recursion repeatedly invokes the mechanism, and consequently the overhead, of method calls. This can be expensive in both processor time and memory space while iteration doesn’t.

  • Recursion makes code smaller while iteration makes it longer.


Memoization makes recursion palatable, but it seems iteration is always faster. Although recursive methods run slower, they sometimes use less lines of code than iteration and for many are easier to understand. Recursive methods are useful for certain specific tasks, as well, such as traversing tree structures.

©2020 by Arturo Devesa.