I was playing around with the following code:
function recaller(){
while(x-- > 0)recaller();
}
var x = 10;
recaller();
alert(x); //-11?
But I was astonished to find that the x now holds the value of -11
I later added alert(x); above the while, to see if it displayed correctly the numbers 10 to 0 and it did.
Can someone explain me where did the -11 came from?, my debugging skills failed me this time and I have no clue how to keep testing
You are recursing into
recaller, soxgets decremented lots of times at the end of the recursion — for each time you recurse, when you exit that recursive call thewhileloop condition will be checked again, and that expression decrementsx. Consider what happens if we start withx = 2:xis 2, we callrecaller(first time) enter its while loop which checksxis greater than zero, decrements and…xis 1, we callrecaller(second time) enter its while loop which checksxis greater than zero, decrements and…xis 0, we callrecaller(third time) enter its while loop which checksxis greater than zero which it isn’t, decrements (-1) and returnsxis greater than zero (no), decrements (-2) and returnsxis greater than zero (no), decrements (-3) and returnsx=-3