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(…).

JavaScript

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

JavaScript

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.

JavaScript

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:

JavaScript

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

JavaScript

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

JavaScript

The output to this snippet is the following:

JavaScript
Advertisement