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
, so x
gets decremented lots of times at the end of the recursion — for each time you recurse, when you exit that recursive call the while
loop condition will be checked again, and that expression decrements x
. Consider what happens if we start with x = 2
:
x
is 2, we call recaller
(first time) enter its while loop which checks x
is greater than zero, decrements and…x
is 1, we call recaller
(second time) enter its while loop which checks x
is greater than zero, decrements and…x
is 0, we call recaller
(third time) enter its while loop which checks x
is greater than zero which it isn't, decrements (-1
) and returnsx
is greater than zero (no), decrements (-2
) and returnsx
is greater than zero (no), decrements (-3
) and returnsx=-3
When you do this:
var x = 10;
alert(x--); // Displays 10
alert(x); // Displays 9
x-- is a post-decrement operator, i.e. executes after the main eval. Thus:
if(x-- > 10) {
// Executes when x is > 10 before decrementing
}
You are doing a recursive looping. I.e. you do:
function recaller(){
while(x-- > 0)recaller();
}
Which:
Since your codition is x > 0
, it will exit from the innermost call to recaller
when x = 0, then decrement once, exit into the next recursive call, etc., until you reach -11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With