DEV Community

Cover image for Recursive function
_Khojiakbar_
_Khojiakbar_

Posted on

Recursive function

What is a Recursive Function in JavaScript?

A recursive function is a function that calls itself in order to solve a problem. It's like a loop, but instead of repeating a block of code, it calls itself with a smaller piece of the problem.

Why Use Recursive Functions?

  1. Breaking Down Problems: Recursive functions are useful when a problem can be divided into smaller, similar problems.

  2. Cleaner Code: For some problems, recursion can make the code simpler and easier to understand compared to using loops.

Key Components

  1. Base Case: This is the condition that stops the recursion. Without it, the function would call itself forever.
  2. Recursive Case: This is where the function calls itself with a smaller part of the problem, moving towards the base case.

Image description

Funny samples:

  1. Running Competition:
function runOrder(countDown) {
    if (countDown <= 0) {
        console.log('Goo...!!!')
        return;
    }
    console.log(countDown)
    runOrder(countDown - 1)
}
runOrder(4);
// 4
// 3
// 2
// 1
// Goo...!!!
Enter fullscreen mode Exit fullscreen mode
  1. Knock Knock
function knockKnock(times) {
    if (times <= 0) {
        console.log(`Who's there?`)
        return
    }
    console.log(times)
    knockKnock(times-1)
}
knockKnock(3);
// 3
// 2
// 1
// Who's there?
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay