What is recursion in JavaScript?

Overview

In this shot, we learn what is recursion and how to implement it in JavaScript.

Recursion is the process of calling itself until something stops the process. In programming, a function is said to be recursive if it calls itself until something stops it.

Recursion allows us to accomplish what loops (for/while) do. Sometimes, the recursion approach is more elegant than using loops.

Syntax

function recurse() {
// function code
recurse()
}
recurse()

Note: The recurse() function calls itself inside the function (Line 3).

How recursion works in JS

Note: When using a recursive function, make sure you have a stop condition (base case) to avoid the function calling itself forever and crashing your browser. This is known as infinite recursion.

Example

In order to see how recursion works, let's write a function that will be counting down from N to 1.

function countDownFrom(number) {
// print the number
console.log(number)
// call the function itself with number - 1
countDownFrom(number - 1)
}
// call the function
countDownFrom(6)

The code above looks fine, but there's an issue. However, the function is missing the stop condition. This is a typical example of infinite recursion. Let's fix the issue.

function countDownFrom(number) {
// base case
if(number == 0) return
// print the number
console.log(number)
// call the function itself with number - 1
countDownFrom(number - 1)
}
// call the function
countDownFrom(6)

Here, we add the base case just at the beginning of the function body (line 3). If the number is 0, end the function execution.

That's all for today. Happy coding!

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources