2

When writing a simple factorial function in its recursive form, we usually just call the function within itself by its own name. This can cause issues if the function is then assigned to some other name and is called via that reference while the original reference is no longer valid, like in the following code.

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

var fact = factorial;

factorial = 5;

console.log(fact(10));

http://jsfiddle.net/4djbq93j/

Now, the obvious fix to this is to call the function inside via arguments.callee but that is invalid in strict mode. Also arguments.callee is not available for arrow functions in ES6.

So my question is essentially this. What is the best practice in writing recursive functions that are decoupled from their name? Also, how do I write an arrow function in ES6 recursively?

Siddharth
  • 1,146
  • 3
  • 15
  • 28
  • Please read the question carefully. This is not a duplicate question. I am asking about arrow functions as well, which are not addressed in your link. – Siddharth Aug 10 '14 at 11:45
  • You should ask the arrow question separately, once you've determined there isn't already a duplicate. For "normal" functions created with a function expression the answer is trivial - give them a name too -it'll only be in scope within the function. – Alnitak Aug 10 '14 at 11:47
  • About ES6 arrow functions, it's recommended to use standard named function expressions, as there is no named arrow function as such. http://esdiscuss.org/topic/self-recursion-and-arrow-functions – Qantas 94 Heavy Aug 10 '14 at 11:48
  • I realized that. But what about the latter part of the question? Would we rather have one more posted question just to address that or reopen this? – Siddharth Aug 10 '14 at 11:49
  • @Qantas94Heavy, the discussion speaks about why arrow functions mustn't have an arguments property of their own. But that doesn't answer my question as to how to write arrow functions recursively. – Siddharth Aug 10 '14 at 11:53
  • Would it not make more sense to place your function inside an object? Make your code a little easier to read after the fact and stop this reassigning issue. – Paddy Aug 10 '14 at 11:57
  • It probably would, @Paddy. I know that. I just wanted alternatives to `arguments.callee` essentially. – Siddharth Aug 10 '14 at 11:58
  • 1
    @Siddharth you just can't. Arrow functions are by definition anonymous, and therefore by definition cannot be recursive. – Alnitak Aug 10 '14 at 13:55

0 Answers0