Create recursive function correctly — JavaScript

A recursive function typically is formed when a function calls itself by name.

Syntax

function recurse() {
if(condition) {
recurse();
}
else {
// stop calling recurse()
}
}

recurse();

A recursive function always has a condition to stop calling itself, otherwise, it will call itself indefinitely.

Generally, recursive functions are used to break down a big problem into smaller ones. You can find that they are heavily used in the data structures like binary trees and graphs and algorithms such as binary search and quicksort.

Let’s have classic example of recursive factorial function.

function factorial(num){
if (num <= 1){
return 1;
} else {
return num * factorial(num-1);
}
}

Although this works initially, it’s possible to prevent it from functioning by running the following code immediately after it:

var anotherFactorial = factorial;
factorial = null;
alert(anotherFactorial(4)); //error!

Here, the factorial()function is stored in a variable called anotherFactorial. The factorial variable is then set to null, so only one reference to the original function remains. When anotherFactorial()is called, it will cause an error, because it will try to execute factorial(), which is no longer a function. Using arguments.calleecan alleviate this problem.

Recall that arguments.callee is a pointer to the function being executed and, as such, can be used to call the function recursively, as shown here

function factorial(num){
if (num <= 1){
return 1;
} else {
return num * arguments.callee(num-1);
}
}

Changing the highlighted line to use arguments.callee instead of the function name ensures that this function will work regardless of how it is accessed. It’s advisable to always use arguments.callee of the function name whenever you’re writing recursive functions.

Do NOT use in strict mode

The value of arguments.callee is not accessible to a script running in strict mode and will cause an error when attempts are made to read it.

Instead, you can use named function expressions to achieve the same result.

var factorial = (function f(num){
if (num <= 1){
return 1;
} else {
return num * f(num-1);
}
});

In this code, a named function expression f()is created and assigned to the variable factorial. The name f remains the same even if the function is assigned to another variable, so the recursive call will always execute correctly.

This pattern works in both nonstrict mode and strict mode.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store