Recursively call an anonymous function without using arguments.callee

How can I call an anonymous function recursively (from within myself)?

(function(n) {
    console.log(n=n-1);
    // Want to call it recursively here without naming any function
})(20);

      

+3


source to share


3 answers


Just name it. In this context, the function will not be available outside the parentheses, so you won't pollute the namespace.



(function recursive(n) {
  console.log(n = n - 1);
  if (n > 0) {
    recursive(n); // just an example
  }
})(20); 

//recursive(20); // won't be able to call it here...

      

+4


source


From a purely theoretical point of view, if you really want to avoid any names, you can use "Y combinator", which is basically a way to call a function with itself as an argument:



(function (le) {
    return (function (f) {
        return f(f);
    }(function (f) {
        return le(function (x) {
            return f(f)(x);
        });
    }));
})(function (f) {
    return function (n) {
        document.write(n + " ");
        if (n > 0) f(n - 1);
    }
})(20);
      

Run codeHide result


Here's a good explanation on how it works.

+2


source


You cannot call it without a name without using arguments.callee

. However, you can call the function like this:

(function repeat(n) {
    console.log(n);
    n = n - 1;
    if (n > 0) repeat(n);
})(20);

      

+1


source







All Articles