DEV Community

Cover image for The brief intro to Recursive functions
Rahul
Rahul

Posted on • Originally published at rahulism.tech

1

The brief intro to Recursive functions

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
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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🤟

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay