What's happening
stackSize is a functional parameter, so it is stored on the stack when the function returns from recursion, the value is accessed from the stack, this is the same value that was passed when the function was called.
When returning from a recursive call, the top frame from the stack is issued, and the parameter values are read from it. Function parameters are stored on the stack , which are not shared between two function calls, even if the same function is called recursively.
What did you expect
You never declared a variable stackSize , so the scope of the variable (parameter) is only in the function. If you declare a variable and do not pass it as a parameter, it will be split.
Below you expect, because the variable is shared, which refers to the same value when returning from a recursive call and returns the same value.
var stackSize = 0; function print(text) { if (!text) { throw 'No text in input !'; } console.log('print : ' + text); } function stack(msg) { stackSize++; print('Stack Entry ' + stackSize); if (stackSize < 4) { stack(msg, stackSize); } else { print(msg); } print('Stack exit ' + stackSize); } stack('foobar', stackSize);
source share