Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where did this -11 came from?

Tags:

javascript

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

like image 430
ajax333221 Avatar asked Nov 30 '22 15:11

ajax333221


2 Answers

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:

  1. x is 2, we call recaller (first time) enter its while loop which checks x is greater than zero, decrements and…
  2. x is 1, we call recaller (second time) enter its while loop which checks x is greater than zero, decrements and…
  3. 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 returns
  4. unwind the stack once to the second time; in its while loop, check x is greater than zero (no), decrements (-2) and returns
  5. unwind the stack once to the first time; in its while loop, check x is greater than zero (no), decrements (-3) and returns
  6. return to top level flow
  7. x=-3
like image 116
James Aylett Avatar answered Dec 09 '22 17:12

James Aylett


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:

  • Compares x to 10
  • Calls recursively
  • Decrements x

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.

like image 44
icyrock.com Avatar answered Dec 09 '22 19:12

icyrock.com