Javascript - Function arguments callee

Introduction

The function internal arguments object is an array-like object that contains all of the arguments that were passed into the function.

The arguments object has a property named callee, which points to its owner function.

Consider the following classic factorial function:

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

It can be decoupled by using arguments.callee as follows:

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

In code above, it no longer references to the name "factorial" in the function body.

It ensures that the recursive call will happen on the correct function no matter how the function is referenced. Consider the following:

var trueFactorial = factorial;
console.log(trueFactorial(5));   //120

Related Topic