Skip to content
Advertisement

Named Function Expression for recursion

As suggested by many people, one of the usages of named function expression is for recursively calling itself. However, it seems that in Chrome Console, function expression without a name can still do so.

Edit : I know this is gonna be stackoverflow, however, I would expect a output like a() is not a function instead of Uncaught RangeError: Maximum call stack size exceeded(…).

var a = function () { 
        a();
        }
a();

the following function expression with a name should be giving me a Uncaught RangeError: Maximum call stack size exceeded(…).

var a = function a () { 
           a();
        }
a();

Edit 2 : In this link https://developer.mozilla.org/en/docs/web/JavaScript/Reference/Operators/function, it says that “If you want to refer to the current function inside the function body, you need to create a named function expression.”. However, it seems to me that the statement is no true, because you can still refer to the current function inside the function body without assigning a function identifier to it

Any thoughts would be appreciated

Advertisement

Answer

You are reaching the stack limit because there are no conditions to limit the recursion.

var a = function (i) { 
        console.log(i);
        if (i >= 10) {
          return;
        }
        else {
          a(++i);
        }
}
a(0);

The above is a better example to show an actual working example of this recursion. Notice how there is a check here whether or not to call the recursive function. The output would be the following:

0
1
2
3
4
5
6
7
8
9
10

You can also have this logic successfully defined at parse time:

function a (i) { 
        console.log(i);
        if (i >= 10) {
          return;
        }
        else {
          a(++i);
        }
}
a(0);

As for the scope of the function definition, this example shows when a() would be defined:

if (typeof a === 'undefined') {
  console.log('a is undefined before the definition');
}
else {
  console.log('a is defined before the definition');
}

var a = function () {
  if (typeof a === 'undefined') {
    console.log('a is undefined inside of a');
  }
  else {
    console.log('a is defined inside of a');
  }
}

a();

if (typeof a === 'undefined') {
  console.log('a is undefined after the definition');
}
else {
  console.log('a is defined after the definition');
}

The output to this snippet is the following:

a is undefined before the definition 
a is defined inside of a 
a is defined after the definition
Advertisement