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.


This content originally appeared on DEV Community and was authored by _Khojiakbar_

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...!!!
  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?


This content originally appeared on DEV Community and was authored by _Khojiakbar_


Print Share Comment Cite Upload Translate Updates
APA

_Khojiakbar_ | Sciencx (2024-06-18T15:44:45+00:00) Recursive function. Retrieved from https://www.scien.cx/2024/06/18/recursive-function/

MLA
" » Recursive function." _Khojiakbar_ | Sciencx - Tuesday June 18, 2024, https://www.scien.cx/2024/06/18/recursive-function/
HARVARD
_Khojiakbar_ | Sciencx Tuesday June 18, 2024 » Recursive function., viewed ,<https://www.scien.cx/2024/06/18/recursive-function/>
VANCOUVER
_Khojiakbar_ | Sciencx - » Recursive function. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/18/recursive-function/
CHICAGO
" » Recursive function." _Khojiakbar_ | Sciencx - Accessed . https://www.scien.cx/2024/06/18/recursive-function/
IEEE
" » Recursive function." _Khojiakbar_ | Sciencx [Online]. Available: https://www.scien.cx/2024/06/18/recursive-function/. [Accessed: ]
rf:citation
» Recursive function | _Khojiakbar_ | Sciencx | https://www.scien.cx/2024/06/18/recursive-function/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.