Skip to main content

What is Recursion?

A function that calls itself.

function func() {
if(/*base case */){ // when to stop the loop
return something;
} else { // recursive case
func(); // call this function
}
}

Factorial Example

// Factorial (!)
// 4! = 4 * 3 * 2 * 1 = 24
// 3! = 3 * 2 * 1 = 6

function factorial(num) {
// when to stop the loop
if (num === 1) {
return num;
} else {
// recursive case
// call this function
return num * factorial(num - 1);
}
}
Breadth First vs Depth First