i wanted to count steps of an infinite recursive function in node.js (v0.4.10), using a global value incrementation. however, the count always pretends to be zero
> c = 0
> (function f() { c++; console.log(c); f() })();
1
2
...
18648
RangeError: Maximum call stack size exceeded
> c
0
logging the c value to console from within the function shows that the value really is incremented, but somehow it is finally reset after that stack accident. even if global.c is used instead of c.
is it the correct bahavior? what is happening here? e.g. in chromium (v14), c holds the final count as expected.
UPDATE
it turns out the above is valid in interactive mode only. when the code is executed from file, and the function in enclosed in try-catch block (to prevent premature exit), the c value is correct..
c = 0;
try {
(function f() { c++; f() })();
} catch(e) {};
console.log(c);
however, there is stil a difference between interactive node.js and chromium javascript console, where the value survives the unhandled exception
Each interactive mode behaves a little bit different than standard execution of JavaScript file (Isaac Schlueter wrote somewhere: “I’ve never seen a REPL that didn’t have at least a tiny bit of magic sprinkled on it“). The interactive mode must evaluate the text, which usually runs the code in a different context.
In case of Node.JS each command is executed in its own context, then REPL takes care to back to us with the results. If we fail in the command due to some errors, the values of our variables remain unchanged (because changed variables ‘die’ in the context of execution). When we run JavaScript file standard way we don’t have this separate context of execution and we directly change our variables.
You can change your example to manually create an error and play wit it:
The final value of
cwill be 0 in REPL as long as the code executes with an error. Because of the error REPL can’t update global value ofcto the value calculated in the execution context of our test function.