JavaScript: Recursive Anonymous Function

I recently saw a question on the forums – How to make a JavaScript anonymous function refer to itself? In other words, how to make an anonymous function in JavaScript call itself from within itself.

The answer is by using arguments.callee.

Let’s see an example. First here’s an example of a recursive function that is not anonymous.

<script type="text/javascript">
function factorial(num) {
  // Round num if not integer.
  num = Math.floor(num);

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

document.writeln(factorial(7));
</script>

The code shown above returns 5040.

Now if the same were to be written as an anonymous function and called recursively, we will use arguments.callee as shown below:

anonymous recursive function
Output remains the same, i.e. 5040.

Note: arguments.callee cannot be defined in “strict” mode and it can behave slow at times.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: