Skip to Content

The brief intro to Recursive functions

A JavasScript function is a block of code designed to perform a particular task. A JavaScript function is executed when somewhere it is invoked.

In this post we're going to learn more about Recursive function in JavaScript. This post is specifically for the JavaScript newbies.

What is Function?

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when somewhere it is invoked.

Working
function new() { // declaring function 
   console.log('function invoked!'); 
}
new(); // function invoked

What is recursive function?

A recursive function that calls itself until it doesn't. This technique is called recursion.

Working

Here, function new is called in a loop like procedure. Initially it invokes from outside of the function and invoked inside the same function until the condition is false. A recursive function should always have condition to stop calling itself, otherwise, it will call itself infinitely.

function new(condition = 1) {
    console.log('function invoked!'); 
    if (condition < 5) {
       new(condition + 1); 
    }
}
new(); 
// function invoked!
// function invoked!
// function invoked!
// function invoked!
// function invoked!

So why recursive function?

The act of a function calling itself, recursion is used to solve problem that contain smaller sub-problems.

A recursive function can receive inputs:

  • a base case or
  • recursive case

When to use recursive function?

Recursive function is used when the same sequence of statements inside the function need to executed with different value and combined together to get final output. Places like sorting algorithms, factorial program, and so on.


āš”Thanks For Reading | Happy CodingšŸ¤Ÿ