spoofskay
spoofskay

Reputation: 1

Javascript ++ -- assistance

Why is the output of this script 5 instead of 8 ?

I thought -- meant -1 twice.

<html>
  <body>
    <script>
      var x = 0;

      var y = 10;

      while ( x < y ){

        x++;

        y-- ;

      }

      document.write(y);
    </script>
  </body>
</html>

Upvotes: 1

Views: 51

Answers (4)

PinkTurtle
PinkTurtle

Reputation: 7041

The ++ operator increments a numerical value by 1 whereas the -- operator does the opposite, decrementing a numerical value by 1.

Here is what happens in your loop :

#Iteration    0       1       2       3       4       5
x value       0       1       2       3       4       5
y value      10       9       8       7       6       5
x < y      true    true    true    true    true   false  <-- breaking here (iteration 5)

From this tab you can see your loop ends at iteration 5 with a value of 5 for x & y.

Let's see what incrementing and decrementing 0 a thousand times does.

var j = 0;

for (var i = 0; i < 1000; i+=1) {
  j++;
}

document.write(j);

document.write('<hr>');

for (var i = 0; i < 1000; i+=1) {
  j--;
}

document.write(j);

Oviously 0 ends up being 1000 and 0 again.

Upvotes: 0

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

--y means decrement by y by 1, so on each loop y decreases by 1.

i.e. y = y - 1

The opposite is happing for ++x. This means on each loop increment x by 1.

i.e. x = x + 1

The loop keeps going until x and y are the same, 5, hence the while loop condition is no longer satisfied, hence breaking the loop.

There is more details on incrementation and decrementation here

Upvotes: 0

Daniel Arechiga
Daniel Arechiga

Reputation: 967

To help you understand better the "++ --" notation: x-- is equivalent of x=x-1 and so on.

Upvotes: 1

MinusFour
MinusFour

Reputation: 14423

First iteration:

x = 0
y = 10

Second Iteration:

x = 1
y = 9

Third Iteration:

x = 2
y = 8

When will x not be smaller than y? When x is equal or bigger than y:

x = 5
y = 5

Upvotes: 1

Related Questions