arguments.callee – Another way of recursion in JavaScript

You may have done recursions while learning or programming. Recursion is a technique where a function calls itself repeatedly until it arrives at a result.
Like other programming languages you can write code to achieve recursion in JavaScript also but this language has something more to offer or can say a different style for achieving the same result.
When we think about recursion, the first problem that comes to our mind is calculating factorial. So, lets create a JavaScript function for it

function factorial(inputNum)
{
  return inputNum<=1?1:(inputNum*factorial(inputNum-1));
}

Same function with arguments.callee

function factorial(inputNum)
{
  return inputNum<=1?1:(inputNum*arguments.callee(inputNum-1));
}

Both the above functions do the same thing but arguments.callee was mainly designed to work with anonymous functions. It can be understood by following example.
Suppose we have to calculate factorial of each element of an array then we might consider writing following code
for it

var arr=[3,5,8,10];
var arrFactorial=arr.map(function(n){
return n<=1?1:(n*/*We do not have a method name to call here*/ (n-1));
});

So arguments.callee solves this problem for us

var arr=[3,5,8,10];
var arrFactorial=arr.map(function(n){
return n<=1?1:(n*arguments.callee(n-1));
});

Hope I was able to explain things to you. Feel free to share this article and share your feedback or suggestions.

You may also like...